<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Exception;//事务处理
use app\admin\model\Sale_pack;//装箱单

class Sale extends Auth
{
    public function __construct(Request $request){
        parent::__construct($request);
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
    }

    
    public function list()
    {   
        isAdd($this->user_id,'empty');
        if(isset($this->data['request']) && $this->data['request'] == 'requestAjax'){
           // $this->needPay(18);
            if(isset($this->data['page']) && $this->data['page']){
                $page = $this->data['page'];
            }else{
                $page = 1;
            }

            if(isset($this->data['limit']) && $this->data['limit']){
                $limit = $this->data['limit'];
            }else{
                $limit = 1000000000;
            }
            // 获取tab下的数据数量
            $typeNum = $this->getTypeNum();

            $where['zu.del_at'] = 0;
            $searchTextjoin = [];
            if(isset($this->data['underwrite']) && $this->data['underwrite'] == 1) $where['zu.underwrite'] = 1;  // 只显示包销单
            if(isset($this->data['whereText']) && $this->data['whereText'] == 'new') $where['zu.is_new'] = 0;  // 新订单
            // 配货中
            if(isset($this->data['whereText']) && $this->data['whereText'] == 'makeId'){    
                $where['zu.make_id'] = ['gt',0];    
                $where['zu.ctn'] = 0;    
            }
            // 待发货
            if(isset($this->data['whereText']) && $this->data['whereText'] == 'delivery'){    
                $where['zu.receive_at'] = 0;    
                $where['zu.ctn'] = ['gt',0];    
                $where['zu.volume'] = ['gt',0];    
            }
            // 已完成
            // if(isset($this->data['whereText']) && $this->data['whereText'] == 'receive') $where['zu.receive_at'] = ['gt',0];  // 已已送货
            if(isset($this->data['whereText']) && $this->data['whereText'] == 'finish') $where['zu.receive_at'] = ['gt',0];  // 已完成
            if(isset($this->data['whereText']) && $this->data['whereText'] == 'del') $where['zu.del_at'] = ['gt',0];        // 已删除

            if(isset($this->data['saler_id']) && $this->data['saler_id']) $where['zu.saler_id'] = $this->data['saler_id'];      
            if(isset($this->data['searchText']) && $this->data['searchText']){      // 搜索
                $where['zu.id|c.name'] = ['like',"%".$this->data['searchText']."%"];        // 已删除
                $searchTextjoin = [['company c','zu.co_id = c.id']];
            } 
            $pageSum = 0;
            if($this->data['whereText'] == 'needPay'){  // 待付款 
                $needPayData = $this->getSaleListNeedPay($where,$page,$limit,$searchTextjoin);
                $saleList = $needPayData['saleList'];
                $pageSum = $needPayData['pageSum'];
                $typeNum['needPayNum']  = $needPayData['pageSum'];
            }else if($this->data['whereText'] == 'future'){ //期货
                $futureData = $this->getSaleListFuture($where,$page,$limit,$searchTextjoin);
                $saleList = $futureData['saleList'];
                $pageSum = $futureData['pageSum'];
                $typeNum['futureNum']  = $futureData['pageSum'];
            }else{
                $allData = $this->getSaleList($this->data['whereText'],$where,$page,$limit,$searchTextjoin);
                $saleList = $allData['saleList'];
                $pageSum = $allData['pageSum'];
            }
            
            // dump($returnData);die;
            if(!empty($saleList)){
                foreach ($saleList as $k => $v) {
                    // dump($v);die;
                    $saleList[$k]['company_name'] = $v['co_id'] ? getValue('company',['id'=>$v['co_id']],'name') : '';
                    $saleList[$k]['branchcompany_name'] = $v['co_branch_id'] ? getValue('co_branch',['id'=>$v['co_branch_id']],'name') : '';
                    $saleList[$k]['saler_name'] = getValue('admin',['id'=>$v['saler_id']],'nickname');

                    $saleList[$k]['create_name'] = getValue('admin',['id'=>$v['create_id']],'nickname');
                    $saleList[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_at']);
                    $saleList[$k]['update_name'] = $v['update_id'] ? getValue('admin',['id'=>$v['update_id']],'nickname') : ''; 
                    $saleList[$k]['update_time'] = $v['update_at'] ? date('Y-m-d H:i:s',$v['update_at']) : '';
                    if($this->data['whereText'] != 'future'){
                        $saleList[$k]['status'] = $this->getsaleStatus($v);
                    }
                    else{
                        // $saleList[$k]['futureProNum'] = Db::name('future_detail')->where(['future_id'=>$v['id']])->count();
                        $saleList[$k]['img_url'] = getImgUrl($v['prochar_id'], 48, $type = 'prochar', $v['prochar_id']);
                    }
                }  
            }
            // dump(serialize($saleList));die;
            $salername = getsalername();
            $ctnStautsNum = Db::name('sale')->where(['ctn'=>0,'make_id'=>['gt',0]])->count();
            return json_encode(array('status'=>1,'data'=>['data'=>$saleList,'pageSum'=>$pageSum,'page'=>$page,'ctnStautsNum'=>$ctnStautsNum,'salername'=>$salername,'typeNum'=>$typeNum]));
        }else if(isset($this->data['request']) && $this->data['request'] == 'getBank'){
            return json_encode($this->getBank());

        }else if(isset($this->data['request']) && $this->data['request'] == 'co_bank'){
            return json_encode($this->co_bank($this->data['company_id']));

        }else if(isset($this->data['request']) && $this->data['request'] == 'getVoucher'){
            return json_encode($this->getVoucher($this->data['company_id']));
            
        }else{
            return view('list',['isshow'=>1]);
        }
    }
    // 获取期货
    function getSaleListFuture($where,$page,$limit,$searchTextjoin)
    {
        $return['saleList'] = Db::name('future')
                    ->alias('zu')
                    ->join([
                        ['future_detail d','zu.id = d.future_id'],
                        ['pro p','d.pro_id = p.id'],
                        ['multi_lang pm','p.mkey = pm.mkey'],
                        ['prochar pc','d.prochar_id = pc.id','LEFT'],
                        ['pro_brand b','p.brand_id = b.id','LEFT'],
                    ])
                    ->join($searchTextjoin)
                    ->field(['zu.*,d.id future_detail_id,d.pro_id,d.prochar_id,d.price,d.qty,pm.content pro_name,pc.model,b.name brand_name'])
                    ->where(['zu.del_id'=>0,'pm.lang'=>$this->lang])
                    ->order('zu.id desc')
                    ->page($page,$limit)
                    ->select();

        $return['pageSum'] = Db::name('future')
                    ->alias('zu')
                    ->join([['future_detail d','zu.id = d.future_id']])
                    ->join($searchTextjoin)
                    ->where(['zu.del_id'=>0])
                    ->count();
        return $return;
    }

    // 获取待付款销售单
    function getSaleListNeedPay($where,$page,$limit,$searchTextjoin)
    {
        $where['zu.ctn'] = ['gt',0];

        $field = ['zu.*'];

        $saleList_ = Db::name('sale')
                    ->alias('zu')
                    ->join([['sale s','zu.id = s.id and s.pay > s.paid'],['sale_pay_index i','zu.id = i.sale_id'],['sale_payreg g','i.sale_payreg_id = g.id']])
                    ->join($searchTextjoin)
                    ->field($field)
                    ->where($where)
                    ->order('zu.id desc')
                    ->select();

        $where['p.paytype_id'] = ['in',$this->payType('A')];
        $saleList = Db::name('sale')
                    ->alias('zu')
                    ->join([['sale s','zu.id = s.id and s.pay > s.paid'],['sale_pay_plan p','s.id = p.sale_id']])
                    ->join($searchTextjoin)
                    ->field($field)
                    ->where($where)
                    ->order('zu.id desc')
                    ->select();
        $data = array_merge($saleList,$saleList_);
        $returnsaleList = [];
        $ids = array_unique(array_column($data, 'id'));
        foreach ($ids as $k => $v) {
            $returnsaleList[] = $data[$k];
        }     
        $return['pageSum'] = count($returnsaleList);
        if($page && $limit) $return['saleList'] = array_slice($returnsaleList, ($page-1)*$limit,$limit);
        return $return;
    }

    function getSaleList($whereText,$where,$page,$limit,$searchTextjoin)
    {
        // dump($this->payType('A'));die;
        $join = [];
        $field = [];
        if($whereText == 'receive'){
            $where['zu.receive_at'] = ['gt',0];
            $where['zu.ctn'] = ['gt',0];
            $where['m.receive_at'] = ['gt',0];
            $join = [
                        ['delivery_note d','zu.id = d.sale_id',"LEFT"],
                        ['sale_make m','zu.id = m.sale_id and d.id = m.delivery_note_id'],
                    ];
            $field = ['zu.*'];       
        }
        else if($whereText == 'delivery'){
            $where['m.package_at'] = ['gt',0];
            $where['m.delivery_at'] = 0;
            $join = [
                        ['sale_make m','zu.id = m.sale_id'],
                    ];
            $field = ['zu.*']; 
        }
        else{
            // $join = [['delivery_note d','zu.id = d.sale_id',"LEFT"]];
            // $field = ['zu.*,d.id delivery_note_id'];
            $join = [];
            $field = ['zu.*'];
        }
        $return['saleList'] = Db::name('sale')
                        ->alias('zu')
                        ->join($join)
                        ->join($searchTextjoin)
                        ->field($field)
                        ->where($where)
                        ->order('zu.id desc')
                        ->page($page,$limit)
                        // ->fetchSql()
                        ->select();
                    // dump($return['saleList']);die;

        $return['pageSum'] = Db::name('sale')
                            ->alias('zu')
                            ->join($join)
                            ->join($searchTextjoin)
                            ->where($where)
                            ->count();
        // dump($return);die;
        return $return;
    }

    function getsaleStatus($sale){
        // dump($sale);die;
        $status = 0;
        if(!empty($sale)){
            $make = DB::name('sale_make')->where(['sale_id'=>$sale['id']])->find();
            if($sale['lowprice'] || $sale['zeroprice']){
                $status = 1;    //"确认中"
            }else if($sale['pledge'] && !$this->payPledge($sale['id']) && !$sale['makefirst']){
                $status = 2;    //"需定金"
            }else if(!$make['id']){
                $status = 3;    //"排队中"
            }else if($make['id'] > 0 && $sale['ctn'] == 0){
                $status = 4;    //"配货中"
            }else if($sale['ctn']>0 && $this->needPay($sale['id']) && $sale['pay']>$sale['paid']){
                $status = 5;    //"待付款"
            }else if($make['package_at'] > 0 ){
                if($sale['ctn'] >0  && $make['delivery_at'] == 0){
                    $status = 6;    //"待发货"
                }else if( $sale['ctn'] >0 &&  $make['delivery_at'] > 0 && $make['receive_at'] == 0 ){
                    $status = 7;    //"送货中"
                }else if( $make['receive_at'] > 0){
                    $status = 8;    // "已送货"
                }
            }else if($sale['finish_at']>0){
                $status = 9;    //"已完成"
            }
        }
        return $status;
    }

    function getTypeNum()
    {
        $where = [];
        if(isset($this->data['saler_id']) && $this->data['saler_id']) $where['saler_id'] = $this->data['saler_id'];     
        $return['allNum'] = Db::name('sale')->where($where)->count();
        $return['newNum'] = Db::name('sale')->where($where)->where(['del_at'=>0,'is_new'=>0])->count();
        $return['makeIdNum'] = Db::name('sale')->where($where)->where(['del_at'=>0,'make_id'=>['gt',0],'ctn'=>0])->count();
        $return['finishNum'] = Db::name('sale')->where($where)->where(['receive_at'=>['gt',0]])->count();
        $return['receiveNum'] = Db::name('sale')->where($where)->where(['receive_at'=>['gt',0]])->count();
        $return['delNum'] = Db::name('sale')->where($where)->where(['del_at'=>['gt',0]])->count();

        $deliveryWhere['zu.receive_at'] = 0;    
        $deliveryWhere['zu.ctn'] = ['gt',0];    
        $deliveryWhere['zu.volume'] = ['gt',0];   
        $return['deliveryNum'] = $this->getSaleList('delivery',$deliveryWhere,1,1,[])['pageSum'];
        // Db::name('sale')->where($where)->where(['ctn'=>['gt',0],'volume'=>['gt',0],'receive_at'=>0])->count();
        
        $return['needPayNum'] = $this->getSaleListNeedPay([],1,1000000,[])['pageSum'];
        return $return;
    }
    // 定金是否已付
    // 已付返回ture
    function payPledge($sale_id)
    {
        // 定金是payplan 登记的当天第一笔款，对应到payreg的这笔款有没有支付。
        $res =  getSearch('sale_pay_index','zu',['zu.*,sp.*'],['zu.sale_id'=>$sale_id,'sp.success_at'=>['gt',0],'sp.check_id'=>['gt',0]],[['sale_payreg sp','zu.sale_payreg_id = sp.id']],'zu.id desc');
        return $res;
    }
    
    // 获取A,B,C类付款方式 Id，字符串
    function payType($likeStr)
    {
        $payType = getDatas('sale_pay_type',['id'],['code'=>['like','%'.$likeStr.'%']]);
        if(!empty($payType)){
            $payType = implode(',',array_column($payType,'id'));
        }
        return $payType;
    }

    // 必须先付款
    // 必须先付返回ture
    function needPay($sale_id)
    {
        // 判断 payplan有没有A类付款方式，或 payreg有没有当天要支付的金额。
        $payType_A = $this->payType('A');
        $payPlan = Db::name('sale_pay_plan')->where(['sale_id'=>$sale_id,'paytype_id'=>['in',$payType_A]])->count();
        $timeWhere = '';
        $timeWhere .= strtotime(date('Y-m-d',time())).',';
        $timeWhere .= strtotime(date('Y-m-d 23:59:59',time()));
        // $payreg = getValue('sale_payreg',['sale_id'=>$sale_id,'pay_day'=>['in',$timeWhere]],'paid');
        $payreg = getSearch('sale_payreg','zu',['*'],['zu.pay_day'=>['in',$timeWhere],'i.sale_id'=>$sale_id],[['sale_pay_index i','zu.id = i.sale_payreg_id']],'zu.id desc');
        if($payPlan || $payreg){
            return true;
        }else{
            return false;
        }
    }

    function isSaleMake($sale_id,$key,$delivery_note_id)
    {
        return getValue('sale_make',['sale_id'=>$sale_id,'delivery_note_id'=>$delivery_note_id],$key); 
    }

    function saleRemark()
    {
        if(isset($this->data['requestType']) && $this->data['requestType'] == 'get'){
            $data = getDatas('sale_remark',['*'],['sale_id'=>$this->data['id'],'sale_detail_id'=>0]);
            foreach ($data as $k => $v) {
                $data[$k]['update_name'] = getValue('admin',['id'=>$v['update_id']],'nickname');
                $data[$k]['update_time'] = getTimeDates($v['update_at'],$this->lang);
            }
            return json_encode($data);
        }elseif(isset($this->data['requestType']) && $this->data['requestType'] == 'save'){
            $sale_ids = array_column(getDatas('sale_remark',['id'],['sale_id'=>$this->data['sale_id'],'sale_detail_id'=>0]), 'id');
            $newIds = [];
            foreach ($this->data['data'] as $k => $v) {
                unset($v['update_name']);
                unset($v['update_time']);
                $v['admin_id'] = $this->user_id;
                $v['update_id'] = $this->user_id;
                $v['update_at'] = time();
                if($v['id'] == 0){
                    $v['create_id'] = $this->user_id;
                    $v['create_at'] = time();
                    $res = insertData('sale_remark',$v);    
                }else{
                    $newIds[] = $v['id'];
                    $res = updateData('sale_remark',['id'=>$v['id']],$v);   
                }
            }
            foreach ($sale_ids as $k1 => $v1) {
                if(!in_array($v1, $newIds)){
                    deleteData('sale_remark',['id'=>$v1]);
                }
            }
            if($res >= 0){
                return json_encode(array('status'=>1,'msg'=>'销售单编号：'.$this->data['sale_id'].'编辑/添加备注成功'));
            }else{
                return json_encode(array('status'=>2,'msg'=>'销售单编号：'.$this->data['sale_id'].'编辑/添加备注失败'));
            }
        }
    }

    // 打印
    function print(){
        return 1;
    }

    public function saleAdd()
    {   
        // 判断是否重复提交
        // if(isAdd($this->user_id,'compare',$this->data)) return json_encode(array('status'=>2,'msg'=>'数据重复提交'));

        if(isset($this->data['request']) && $this->data['request'] == 'insert'){
            // dump($this->data);die;
            $noticeText = noticeText( $this->data,['data'=>'完善订单数据','orderList'=>'完善产品数据','paymentList'=>'完善付款安排数据'],'','isset');
            if($noticeText['status'] == 2) return json_encode(array('status'=>2,'msg'=>'添加失败:'.$noticeText['msg']));
            $noticeText = noticeText( $this->data['data'],['companyId'=>'客户','saler_id'=>'业务员','saleDeliveryTypeId'=>'送货方式']);
            if($noticeText['status'] == 2) return json_encode(array('status'=>2,'msg'=>'添加失败:'.$noticeText['msg']));

            // 添加订单
            $sale_id = $this->implementSaleSql('insert',$this->data['data']);
            if(is_array($sale_id)){
                return json_encode($sale_id);
            }else{
                // 添加订单的备注
                if(isset($this->data['saleOrderRemarkData']))
                    $saleRemark_id = $this->implementSaleRemark('insert',$this->data['saleOrderRemarkData'],$sale_id);

                // 添加订单明细
                $saleDetail_id = $this->implementSaleDetail('insert',$this->data['orderList'],$sale_id);

                // 添加订单费用明细
                if(isset($this->data['costData']))
                    $costData_id = $this->implementSaleCostDetail('insert',$this->data['costData'],$sale_id);

                // 添加订单付款安排
                $payplan_id = $this->implementSalePayPlanDetail('insert',$this->data['paymentList'],$sale_id);

                insertData('sale_log',['sale_id'=>$sale_id,'option'=>'change','remark'=>'销售单开单成功','create_id'=>$this->user_id,'create_at'=>time()]);

                return json_encode(array('status'=>1,'msg'=>'添加成功'));
            }

        }else if(isset($this->data['request']) && $this->data['request'] == 'add'){
            // 送货方式
            $returnData['saleDeliveryTypeList'] = getSearch('sale_delivery_type','zu',['zu.id,mu.content'],['mu.lang'=>$this->lang],[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id desc');
            // 费用类型
            $returnData['saleCostType'] = getDatas('sale_cost_type',['id,name,options']);
            // 付款方式
            $returnData['salePayType'] = [];
            $salePayType = $this->getCoSale(0,0);
            if($salePayType) $returnData['salePayType'] = $salePayType['salePayType'];
            // 产品分类
            $returnData['proType'] = getSearch('procat','zu',['zu.id,zu.pid,mu.content'],['mu.lang'=>$this->lang],[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id desc');
            $returnData['proType'] = getTree($returnData['proType']);

            // 产品分类
            $proCate = getSearch('procat','zu',['zu.id,zu.pid,mu.content'],['mu.lang'=>$this->lang],[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id desc');
            $returnData['proCate'] = getTree($proCate);

            // 收款账号
            $returnData['receivingAccount'] = $this->accounts();

            // 付款安排快捷输入
            $returnData['quickInput'] = $this->getquickInput();
            // dump($returnData);die;
            return json_encode(array('status'=>1,'data'=>$returnData));
        }else if(isset($this->data['request']) && $this->data['request'] == 'status'){
            return json_encode($this->proStoreStatus($this->data['pro_id'],$this->data['prochar_id'],$this->data['prochar_qty']));

        }else if(isset($this->data['request']) && $this->data['request'] == 'storeType'){
            return json_encode($this->isNormalSaleOrder($this->data['pro_id'],$this->data['prochar_id'],$this->data['prochar_qty']));

        }else if(isset($this->data['request']) && $this->data['request'] == 'invoiceType'){ // 获取发票类型
            return json_encode($this->getInvoiceType());

        }else if(isset($this->data['request']) && $this->data['request'] == 'saleRecording'){ // 获取发票类型
            return json_encode($this->getSaleRecording());

        }else{
            return view('saleopen',['title'=>'新增销售订单','requestType'=>'add','create_id'=>$this->user_id,'create_name'=>session('admin')['nickname']]);
        }
    }

    function getquickInput()
    {   
        /**
        *   id:付款方式ID，sale_pay_type.id
        *   day:多少天后
        *   percentage:付款占比
        **/ 
        $arr =  [
                    ['id'=>1,'name'=>'现金','data'=>[
                                                        ['day'=>0,'percentage'=>100],
                                                    ]
                    ],
                    ['id'=>7,'name'=>'期帐','data'=>[
                                                        ['day'=>30,'percentage'=>100],
                                                    ]
                    ],
                    ['id'=>7,'name'=>'期帐','data'=>[
                                                        ['day'=>0,'percentage'=>30],
                                                        ['day'=>30,'percentage'=>70],
                                                    ]
                    ],
                    ['id'=>3,'name'=>'现金支票','data'=>[
                                                        ['day'=>0,'percentage'=>30],
                                                        ['day'=>30,'percentage'=>70],
                                                    ]
                    ],
                    ['id'=>5,'name'=>'转账','data'=>[
                                                        ['day'=>0,'percentage'=>30],
                                                        ['day'=>30,'percentage'=>30],
                                                        ['day'=>30,'percentage'=>40],
                                                    ]
                    ],
                ];
        return $arr;
    }

    // 添加销售订单
    function implementSaleSql($type,$data)
    {   
        // dump($data);die;
        if(getValue('warehouse2admin',['admin_id'=>$data['saler_id']],'warehouse_id')){

            $res = 0;
            if(!empty($data)){
                $insertData['saler_id'] = $data['saler_id'];
                $insertData['warehouse_id'] = getValue('warehouse2admin',['admin_id'=>$this->user_id],'warehouse_id');
                $insertData['priority'] = $data['priority'];
                $insertData['delivery_type_id'] = $data['saleDeliveryTypeId'];
                $insertData['co_id'] = $data['companyId'];
                $insertData['co_branch_id'] = $data['branchCompanyId'];
                $insertData['trans_id'] = $data['logisticsCompanyId'];
                $insertData['underwrite'] = $data['underwrite'] == 'true' ? 1 : 0;
                $insertData['makefirst'] = $data['makefirst'] == 'true' ? 1 : 0;
                $insertData['pledge'] = $data['pledge'] == 'true' ? 1 : 0;
            // dump($insertData['pledge']);die;
                $insertData['sign_id'] = $data['saler_id'];
                $insertData['total'] = $data['total'];
                $insertData['discount'] = $data['discount'];
                $insertData['cost'] = $data['cost'];
                $insertData['pay'] = $data['pay'];
                $insertData['paid'] = $data['paid'];
                $insertData['commission'] = $data['commission'];
                $insertData['profit'] = $data['pay'] - $data['discount'] - $data['commission'] - $data['cost'];
                // dump($insertData);die;
                if(isset($data['salePayBill']) && $data['salePayBill'] ) $insertData['accounts_id'] = isset($data['accounts_id']) ? $data['accounts_id'] : 0 ;
                // $insertData['ctn'] = $data['ctn'];
                // $insertData['volume'] = isset($data['volume']) ? $data['volume'] : 0;
                $insertData['ctn'] = 0;
                $insertData['volume'] = 0;
                $insertData['update_id'] = $this->user_id;
                $insertData['update_at'] = time();
                if($type == 'insert'){
                    $insertData['create_id'] = $this->user_id;
                    $insertData['create_at'] = time();
                    $res = insertData('sale',$insertData);
                    if(isset($data['salePayBill']) && $data['salePayBill'] ){   //  是判断是否存在银行单付款安排
                        $res1 = insertData('sale_invoice',['sale_id'=>$res,'invoice_type_id'=>$data['invoiceTypeId'],'create_id'=>$this->user_id,'create_at'=>time()]);
                    }
                }else if($type == 'update'){
                    $insertData['update_id'] = $this->user_id;
                    $insertData['update_at'] = time();
                    $res = updateData('sale',['id'=>$data['saleOrderNo']],$insertData);

                    if(isset($data['salePayBill']) && $data['salePayBill'] ){   // 编辑销售单时  是判断是否存在银行单付款安排
                        $res2 = updateData('sale_invoice',['sale_id'=>$data['saleOrderNo']],['invoice_type_id'=>$data['invoiceTypeId'],'update_id'=>$this->user_id,'update_at'=>time(),'del_id'=>0,'del_at'=>0]);
                    }else{
                        $res2 = updateData('sale_invoice',['sale_id'=>$data['saleOrderNo']],['del_id'=>$this->user_id,'del_at'=>time()]);
                    }
                }

            } 
            return $res;
        }else{
            return array('status'=>2,'msg'=>'添加失败，请绑定所在仓库');
        }
        
    }

    // 添加销售订单备注
    function implementSaleRemark($type,$data,$sale_id)
    {
        $res = 0;
        if(!empty($data) && $sale_id){
            foreach ($data as $k => $v) {
                $insertData['sale_id'] = $sale_id;
                $insertData['sale_detail_id'] = isset($v['sale_detail_id']) ? $v['sale_detail_id'] : 0;
                $insertData['add'] = (isset($v['add']) && $v['add']) ? 1 : 0;
                $insertData['private'] = (isset($v['private']) && $v['private']) ? 1 : 0;
                $insertData['show2make'] = (isset($v['rationed']) && $v['rationed']) ? 1 : 0;
                $insertData['remark'] = isset($v['content']) ? $v['content'] : (isset($v['remark']) ? $v['remark'] : '' );
                $insertData['admin_id'] = $this->user_id;
                $insertData['update_id'] = $this->user_id;
                $insertData['update_at'] = time();
                if($type == 'insert' || (isset($v['isset']) && $v['isset'] == 'false')){
                    $insertData['create_id'] = $this->user_id;
                    $insertData['create_at'] = time();
                    $res = insertData('sale_remark',$insertData);    
                }else if($type == 'update' && !isset($v['isset'])){
                    $res = updateData('sale_remark',['id'=>$v['id']],$insertData);   
                }
            }
        }
        return $res;
    }   


    // 添加销售订单明细
    function implementSaleDetail($type,$data,$sale_id)
    {   
        $res = 0;
        if(!empty($data) && $sale_id){
            $isLowprice = 0;
            foreach ($data as $k => $v) {
                if(isset($v['storeType']) && $v['storeType'] == "futures"){   // 判断是否期货
                    $future['saler_id'] = $this->user_id;
                    $future['co_id'] = getValue('sale',['id'=>$sale_id],'co_id');
                    $future['co_branch_id'] = getValue('sale',['id'=>$sale_id],'co_branch_id');
                    $future['total'] = $v['orderPrice']*$v['orderNum'];
                    $future['update_id'] = $this->user_id;
                    $future['update_at'] = time();
                    if($type == 'insert' || (isset($v['isset']) && $v['isset'] == 'false')){
                        $future_id = insertData('future',$future);
                    }else if($type == 'update' && !isset($v['isset'])){
                        $res = updateData('future',['id'=>$v['id']],$future);
                        $future_id = $v['id'];
                    }
                    $future_detail = [];
                    $future_detail['pro_id'] = $v['pro_id'];
                    $future_detail['prochar_id'] = $v['prochar_id'];
                    $future_detail['price'] = $v['orderPrice'];
                    $future_detail['qty'] = $v['orderNum'];
                    $future_detail['future_id'] = $future_id;

                    if($type == 'insert' || (isset($v['isset']) && $v['isset'] == 'false')){
                        $future['create_id'] = $this->user_id;
                        $future['create_at'] = time();
                        $future_detail = insertData('future_detail',$future_detail);

                    }else if($type == 'update' && !isset($v['isset'])  ){
                        $future_detail = updateData('future_detail',['id'=>$v['id']],$future_detail);
                    }
                }else{
                    $insertData['sale_id'] = $sale_id;
                    $insertData['pro_id'] = $v['pro_id'];
                    $insertData['prochar_id'] = $v['prochar_id'];
                    $insertData['price'] = $v['orderPrice'];
                    $insertData['qty'] = $v['orderNum'];
                    $insertData['profit'] = $v['orderPrice'] - $this->getProSale($v['pro_id'],$v['prochar_id'],'cif'); // 毛利润 
                    $insertData['undone_qty'] = $v['orderNum'];
                    $insertData['commission'] = isset($v['commission']) ? $v['commission'] :0;
                    $insertData['discount'] = isset($v['discountType']) && $v['discountType'] == "%" ? 0 - (isset($v['discount']) ? $v['discount'] : 0) : (isset($v['discount']) ? $v['discount'] : 0);   // 负数为百分比
                    $insertData['add'] = 0;
                    if($type == 'insert' || (isset($v['isset']) && $v['isset'] == 'false')){
                        $res = insertData('sale_detail',$insertData);
                        $sale_detail = $res;
                        // 累加store sale_qty
                        $storeSetIncOrSetDecType = 'setInc';
                        $olddetailQty = 0;
                    }else if($type == 'update' && !isset($v['isset']) ){
                        // 获取编辑前qty 数据
                        $olddetail = Db::name('sale_detail')->where(['id'=>$v['id']])->find();
                        $olddetailQty = $olddetail['qty'];
                        $res = updateData('sale_detail',['id'=>$v['id']],$insertData);
                        $sale_detail = $v['id'];
                        $this->insertSaleLog_($sale_id,$olddetail,$insertData,$v['pro_name'],$v['model']);
                        $storeSetIncOrSetDecType = 'setDec';
                    }
                    $storeSetIncOrSetDecWhere = ['pro_id'=>$v['pro_id'],'prochar_id'=>$v['prochar_id'],'warehouse_id'=>getValue('sale',['id'=>$sale_id],'warehouse_id'),'place_id'=>0];
                    if(isset($storeSetIncOrSetDecType))
                        $this->storeSetIncOrSetDec($storeSetIncOrSetDecWhere,$storeSetIncOrSetDecType,$v['orderNum'],$olddetailQty);
                    if(isset($v['remarksList'])){
                        foreach ($v['remarksList'] as $k1 => $v1) {
                            if($v1['add']) $res1 = updateData('sale_detail',['id'=>$sale_detail],['add'=>1]);
                            $remarksList['sale_id'] = $sale_id;
                            $remarksList['sale_detail_id'] = $sale_detail;
                            $remarksList['add'] = isset($v1['add']) && $v1['add'] == 'true' ? 1 : 0;
                            $remarksList['private'] = isset($v1['private']) && $v1['private'] == 'true' ? 1 : 0;
                            $remarksList['show2make'] = isset($v1['rationed']) && $v1['rationed'] == 'true' ? 1 : 0;
                            $remarksList['update_id'] = $this->user_id;
                            $remarksList['update_at'] = time();


                            $remarksList['admin_id'] = $this->user_id;
                            if(isset($v1['remark']) && $v1['remark']) $remarksList['remark'] = $v1['remark'];
                            if(isset($v1['content']) && $v1['content']) $remarksList['remark'] = $v1['content'];

                            if($type == 'insert' || (isset($v1['isset']) && $v1['isset'] == 'false')){    // 判断是否已存在。isset == true 则编辑数据，false 则添加
                                $remarksList['create_id'] = $this->user_id;
                                $remarksList['create_at'] = time();
                                $res = insertData('sale_remark',$remarksList);  
                            }else if($type == 'update' && !isset($v['isset'])  ){
                                $res = updateData('sale_remark',['id'=>$v1['id']],$remarksList);  
                            }
                            
                        }
                    }
                }
                // 判断是否有价格错误
                if($v['orderPrice'] == 0) $isLowprice = 1;
            }
            if($isLowprice == 0){
                $this->isLowprice($sale_id,false);
            }else{
                $this->isLowprice($sale_id,true);
            }
        }
        return $res;
    }

    function storeSetIncOrSetDec($where,$type,$qty,$oldQty=0){

        if(!hasData('store',$where)){
            $insertData = $where;
            $insertData['place_id'] = 0;
            $insertData['qty'] = 0;
            $insertData['sale_qty'] = 0;
            insertData('store',$insertData);
        }

        if($type == 'setInc'){
            Db::name('store')->where($where)->setInc('sale_qty',$qty);
            // $where['warehouse_id'] = 0;
            // Db::name('store')->where($where)->setInc('sale_qty',$qty);
        }else{
            if($oldQty != 0) Db::name('store')->where($where)->setDec('sale_qty',$oldQty);
            Db::name('store')->where($where)->setInc('sale_qty',$qty);
            // $where['warehouse_id'] = 0;
            // if($oldQty != 0) Db::name('store')->where($where)->setDec('sale_qty',$oldQty);
            // Db::name('store')->where($where)->setInc('sale_qty',$qty);
        }
    }

    function isLowprice($sale_id,$type)
    {
        if($type){
            $res = updateData('sale',['id'=>$sale_id],['zeroprice'=>1,'lowprice'=>1,'lock_at'=>time()]);
        } else {
            $res = updateData('sale',['id'=>$sale_id],['zeroprice'=>0,'lowprice'=>0]);
        }
    }

    // 销售订单费用明细
    function implementSaleCostDetail($type,$data,$sale_id)
    {
        $res = 0;
        if(!empty($data) && $sale_id){
            foreach ($data as $k => $v) {
                $insertData['sale_id'] = $sale_id;
                $insertData['cost_type_id'] = $v['saleCostTypeId'];
                $insertData['amount'] = $v['costPrice'];
                $insertData['update_id'] = $this->user_id;
                $insertData['update_at'] = time();
                // 费用明细 备注信息
                $insertRemarkData['sale_id'] = $sale_id;
                $insertRemarkData['remark'] = $v['costRemarks'];

                if($type == 'insert' || (isset($v['isset']) && $v['isset'] == 'false')){
                    $insertData['create_id'] = $this->user_id;
                    $insertData['create_at'] = time();
                    $res = insertData('sale_cost',$insertData);   

                    $insertRemarkData['sale_cost_id'] = $res;
                    $res1 = insertData('sale_cost_remark',$insertRemarkData); 
                }else if($type == 'update' || !isset($v['isset'])){
                    $insertData['update_id'] = $this->user_id;
                    $insertData['update_at'] = time();
                    $res = updateData('sale_cost',['id'=>$v['id']],$insertData); 

                    $res1 = updateData('sale_cost_remark',['sale_cost_id'=>$v['id']],$insertRemarkData);
                }
            }
        }
        return $res;
    }

    // 销售订单付款安排
    function implementSalePayPlanDetail($type,$data,$sale_id)
    {
        $res = 0;
        if(!empty($data) && $sale_id){
            foreach ($data as $k => $v) {
                $insertData['sale_id'] = $sale_id;
                $insertData['paytype_id'] = $v['paytype_id'];
                $insertData['pay_day'] = strtotime($v['paymentDay']);    
                $insertData['amount'] = $v['paymentAmount'];    
                $insertData['update_id'] = $this->user_id;
                $insertData['update_at'] = time();
                if($type == 'insert' || (isset($v['isset']) && $v['isset'] == 'false' )){
                    $insertData['create_id'] = $this->user_id;    
                    $insertData['create_at'] = time(); 
                    $res = insertData('sale_pay_plan',$insertData);  
                    $sale_payplan_id = $res;
                }else if($type == 'update' && !isset($v['isset'])){

                    $insertData['update_id'] = $this->user_id;    
                    $insertData['update_at'] = time(); 
                    $res = updateData('sale_pay_plan',['id'=>$v['id']],$insertData);
                    $sale_payplan_id = $v['id'];
                }
                 
                if(isset($v['remarksList'])){
                    foreach ($v['remarksList'] as $k1 => $v1) {
                        $remarksList['sale_payplan_id'] = $sale_payplan_id; 
                        $remarksList['remark'] = $v1['content']; 
                        $remarksList['update_id'] = $this->user_id; 
                        $remarksList['update_at'] = time(); 
                        if(isset($v1['isset']) && $v1['isset'] == 'false'){
                            $res1 = insertData('sale_payplan_remark',$remarksList);
                        }else if(!isset($v1['isset'])){
                            $res1 = updateData('sale_payplan_remark',['id'=>$v1['id']],$remarksList);
                        }
                    }
                }  
            }
        }
        return $res;
    }

    // 付款登记数据
    function implementSalePayregDetail($data,$sale_id)
    {
        $res = 0;
        if(!empty($data)){
            foreach ($data as $k => $v) {
                $insertData['co_id'] = $v['co_id'];
                $insertData['paytype_id'] = $v['paytype_id'];
                // 现金 和代金券时 系统默认数据
                $insertData['paid'] = $v['paytype_id'] == 2 ? $v['amount'] : 0; 
                $insertData['check_id'] = $v['paytype_id'] == 2 ? $this->user_id : 0; 
                $insertData['amount'] = $v['amount'];
                $insertData['update_at'] = time();
                $insertData['update_id'] = $this->user_id;


                if(isset($v['isset']) && $v['isset'] == 'false'){
                    $insertData['success_at'] = $v['paytype_id'] == 2 ? time() : 0; 
                    $insertData['pay_day'] = $v['paytype_id'] == 1 || $v['paytype_id'] == 2 ? time() : strtotime($v['pay_day']);
                    $insertData['create_at'] = time();
                    $insertData['create_id'] = $this->user_id;
                    $sale_payreg_id = insertData('sale_payreg',$insertData);
                    // 添加关联表 关联数据
                    $sale_pay_index = insertData('sale_pay_index',['co_id'=>$v['co_id'],'sale_id'=>$sale_id,'sale_payplan_id'=> (isset($v['sale_payplan_id']) ? $v['sale_payplan_id'] : 0),'sale_payreg_id'=>$sale_payreg_id]);
                }else{
                    $insertData['success_at'] = $v['paytype_id'] == 2 ? $v['success_at'] : 0; 
                    $insertData['pay_day'] = strtotime($v['pay_day']);
                    $res = updateData('sale_payreg',['id'=>$v['id']],$insertData);
                    $sale_payreg_id = $v['id'];
                }

                // 整理 付款登记 详情数据，
                if(isset($v['payregDetail'])){
                    foreach ($v['payregDetail'] as $k1 => $v1) {
                    
                        // $payregDetail['sale_id'] = $sale_id;
                        // $payregDetail['sale_payreg_id'] = $sale_payreg_id;
                        switch ($v['paytype_id']) {
                            case '2':   // 代金券
                                $table = 'voucher';

                                $voucher['sale_id'] = $sale_id;
                                $voucher['sale_payreg_id'] = $sale_payreg_id;
                                $res = updateData('voucher',['id'=>$v1['id']],$voucher);
                                break;
                            case '3' :  // 现金支票
                            case '4':   // 期票
                                $table = 'sale_pay_cheque';
                                $sale_pay_cheque['sale_id'] = $sale_id;
                                $sale_pay_cheque['sale_payreg_id'] = $sale_payreg_id;
                                $sale_pay_cheque['bank_id'] = $v1['bank_id'];
                                $sale_pay_cheque['number'] = isset($v1['chequeNo']) ? $v1['chequeNo'] : $v1['number'] ;
                                $sale_pay_cheque['signature'] = isset($v1['chequeSignature']) ? $v1['chequeSignature'] : $v1['signature'] ;
                                $sale_pay_cheque['pay_day'] = isset($v1['chequeDay']) ? strtotime($v1['chequeDay']) : $v1['pay_day'] ;
                                $sale_pay_cheque['amount'] = isset($v1['chequePrice']) ? $v1['chequePrice'] : $v1['amount'] ;
                                $sale_pay_cheque['update_id'] = $this->user_id;
                                $sale_pay_cheque['update_at'] = time();
                                // $sale_pay_cheque['signature'] = $v1['chequeSignature'];
                                // $sale_pay_cheque['pay_day'] = strtotime($v1['chequeDay']);
                                // $sale_pay_cheque['amount'] = $v1['chequePrice'];
                                $sale_pay_cheque['scan_url'] = isset($v1['scan_url']) ? $v1['scan_url'] : '';
                                if(isset($v1['isSave'])){
                                    $sale_pay_cheque['create_id'] = $this->user_id;
                                    $sale_pay_cheque['create_at'] = time();
                                    $res = insertData('sale_pay_cheque',$sale_pay_cheque);
                                }else{
                                    $res = updateData('sale_pay_cheque',['id'=>$v1['id']],$sale_pay_cheque);
                                }
                                
                                break;
                            case '5':   // 转账
                                $table = 'sale_pay_transfer';
                                $sale_pay_transfer['sale_id'] = $sale_id;
                                $sale_pay_transfer['sale_payreg_id'] = $sale_payreg_id;
                                if(isset($v1['co_bank_id'])) $sale_pay_transfer['co_bank_id'] = $v1['co_bank_id'];
                                if(isset($v1['transferOutId']) && $v1['transferOutId'] >= 0) $sale_pay_transfer['co_bank_id'] = $v1['transferOutId'];
                                $sale_pay_transfer['pay_day'] = isset($v1['transferDay']) ? strtotime($v1['transferDay']) : $v1['pay_day'];
                                $sale_pay_transfer['number'] = isset($v1['transferNo']) ? $v1['transferNo'] : $v1['number'];
                                $sale_pay_transfer['amount'] = isset($v1['transferPrice']) ? $v1['transferPrice'] : $v1['amount'];
                                if(isset($v1['scan_url'])) $sale_pay_transfer['scan_url'] = $v1['scan_url'];
                                if(isset($v1['transferscan_url'])) $sale_pay_transfer['scan_url'] = $v1['transferscan_url'];
                                $sale_pay_transfer['account_id'] = isset($v1['transferInId']) ? $v1['transferInId'] : $v1['account_id'];
                                $sale_pay_transfer['update_id'] = $this->user_id;
                                $sale_pay_transfer['update_at'] = time();
                                // $sale_pay_transfer['pay_day'] = strtotime($v1['transferDay']);
                                // $sale_pay_transfer['number'] = $v1['transferNo'];
                                // $sale_pay_transfer['amount'] = $v1['transferPrice'];
                                // $sale_pay_transfer['scan_url'] = $v1['scan_url'];
                                // $sale_pay_transfer['account_id'] = $v1['transferInId'];

                                if(isset($v1['isSave'])){
                                    $sale_pay_transfer['create_id'] = $this->user_id;
                                    $sale_pay_transfer['create_at'] = time();
                                    $res = insertData('sale_pay_transfer',$sale_pay_transfer);
                                }else{
                                    $res = updateData('sale_pay_transfer',['id'=>$v1['id']],$sale_pay_transfer);
                                }
                                break;
                        }
                    }
                }
                

            }
        }
        return $res;
    }


    // 销售送货单
    function implementDeliveryNote($data,$sale_id,$sqlStatus)
    {
        $delivery_note_id = 0;
        if(!empty($data)){
            $insertData['ctn'] = $data['ctn'];
            $insertData['sale_id'] = $sale_id;
            $insertData['co_id'] = $data['co_id'];
            $insertData['volume'] = $data['volume'];
            $insertData['priority'] = $data['priority'];
            $insertData['co_branch_id'] = $data['co_branch_id'];
            $insertData['delivery_type_id'] = $data['delivery_type_id'];
            $insertData['update_at'] = time();
            $insertData['update_id'] = $this->user_id;
            if($sqlStatus == 'add'){
                $insertData['create_id'] = $this->user_id;
                $insertData['create_at'] = time();
                $delivery_note_id = insertData('delivery_note',$insertData);
            }else{
                $res = updateData('delivery_note',['id'=>$data['id']],$insertData);
                $delivery_note_id = $data['id'];
            }
            if(isset($data['detail'])){
                foreach ($data['detail'] as $k1 => $v1) {
                    $detail['sale_id'] = $sale_id;
                    $detail['delivery_note_id'] = $delivery_note_id;
                    $detail['pro_id'] = $v1['pro_id'];
                    $detail['prochar_id'] = $v1['prochar_id'];
                    $detail['qty'] = isset($v1['qty']) ? $v1['qty'] : 0;
                    if($v1['id']){
                        $sqlStatus_ = 'edit';
                        $res = updateData('delivery_note_detail',['id'=>$v1['id']],$detail);
                        $detail_id = $v1['id'];
                    }else{
                        $sqlStatus_ = 'add';
                        $detail_id = insertData('delivery_note_detail',$detail);
                    }
                    if($v1['remark']){
                        $this->deliveryNoteRemark($v1,$delivery_note_id,$detail_id,$sqlStatus_,'detail');
                    }
                }    
            }
            if($data['remark']){
                $this->deliveryNoteRemark($data,$delivery_note_id,0,$sqlStatus);
            }
        }
        return $delivery_note_id;
    }
    function deliveryNoteRemark($data,$delivery_note_id,$detail_id,$sqlStatus,$type='')
    {
        $remark['sale_id'] = $data['sale_id'];
        $remark['delivery_note_id'] = $delivery_note_id;
        $remark['detail_id'] = $detail_id;
        $remark['remark'] = $data['remark'];
        $remark['update_at'] = time();
        $remark['update_id'] = $this->user_id;
        if($sqlStatus == 'add'){
            $remark['create_id'] = $this->user_id;
            $remark['create_at'] = time();
            $delivery_note_remark = insertData('delivery_note_remark',$remark);
        }else{
            if($type == 'detail'){
                $delivery_note_remark = updateData('delivery_note_remark',['detail_id'=>$data['id']],$remark);
            }else{
               $delivery_note_remark = updateData('delivery_note_remark',['delivery_note_id'=>$data['id'],'detail_id'=>0],$remark); 
            }
        }
    }


    // 删除规则，sale_detail 硬删除，sale_cost 业务员软删除，管理员清除，sale_payreg 业务员软删除，管理员清除，sale_pay_plan 硬删除
    // 删除数据
    function delList($data,$sale_id)
    {   
        foreach ($data as $k => $v) {
            switch ($k) {
                case 'saleOrderRemarkData':             // 销售单备注
                case 'addRemarksData':                  // 销售单明细备注
                    $table = "sale_remark";
                    $res = deleteData($table,'1=1',$v);
                    break;      
                case 'orderList':                       // 销售订单明细    
                    $table = "sale_detail";         
                    $this->deldata('del',$table,$v,'sale_detail_id','sale_remark');
                    break;
                case 'futures':                         // 期货订单
                    $table = "future";                  // 软删除，因此不需要传 当前table 下的子级数据表名，和删除条件key
                    $this->deldata('del',$table,$v);
                    break;
                case 'costData':                        // 销售订单费用明细
                    $table = "sale_cost";
                    $this->deldata('update',$table,$v,'sale_cost_id','sale_cost_remark');
                    break;
                case 'paymentRemarksDataList':          // 付款安排备注
                    $table = "sale_payplan_remark";
                    $res = deleteData($table,'1=1',$v);
                    break;
                case 'paymentList':                     // 付款安排明细
                    $table = "sale_pay_plan";
                    $this->deldata('del',$table,$v);
                    break;
                case 'payregList':                      // 付款登记明细
                    $table = "sale_payreg";
                    $this->delpayregList($table,$v);
                    break;
                case 'deliveryNoteRemarkContent':       // 送货单备注
                    $table = "delivery_note_remark";
                    $res = deleteData('del',$table,'1=1',$v);
                    break;
                case 'deliveryNoteList':                // 送货单明细
                    $table = "delivery_note";
                    $this->deldata('del',$table,$v,'delivery_note_id','delivery_note_remark',false);
                    $this->deldata('del',$table,$v,'delivery_note_id','delivery_note_detail');
                    break;
            }
        }
    }
    // 清除数据
    function clearList($data,$sale_id)
    {   
        foreach ($data as $k => $v) {
            switch ($k) {
                case 'costData':                        // 销售订单费用明细
                    $table = "sale_cost";
                    $this->deldata('del',$table,$v,'sale_cost_id','sale_cost_remark');
                    break;
                case 'payregList':                      // 付款登记明细
                    $table = "sale_payreg";
                    $this->delpayregList($table,$v,'del');
                    break;
            }
        }
    }
    /**
    *   $sqlType:数据库操作，del = 实删除，update = 软删除
    *   $table：主表表名
    *   $data : 删除数据的 Id
    *   $key：子表where条件字段
    *   $childTable：子表表名
    *   $type：是否删除主表
    **/
    function deldata($sqlType,$table,$data,$key='',$childTable='',$type=true)
    {
        if($key){
            foreach ($data as $k => $v) {
                if($sqlType == 'del') $res = Db::name($childTable)->where([$key=>$v])->delete();
            }    
        }
        
        if($sqlType == 'del'){
            if($type){
                if($sqlType = 'del'){
                    if($table == 'sale_detail'){
                        foreach ($data as $k2 => $v2) {
                            $pro_ = Db::name('sale_detail')->where(['id'=>$v2])->find();
                            $pro_name = getValue('multi_lang',['mkey'=>'pro_'.$pro_['pro_id'],'lang'=>$this->lang],'content');
                            $model = getValue('prochar',['id'=>$pro_['prochar_id']],'model');
                            $model = $model?$model:'-';
                            $this->insertSaleLog($pro_['sale_id'],'删除产品：'.$pro_name.' 型号:'.$model);    
                        }
                    }
                    $res = deleteData($table,'1=1',$data);
                } 
            } 
        }
        if($sqlType == 'update'){
            foreach ($data as $k1 => $v1) {
                $res = Db::name($table)->where(['id'=>$v1])->update(['del_at'=>time(),'del_id'=>$this->user_id]);
            }
        }
    }

    function delpayregList($table,$data,$type='update')
    {
        foreach ($data as $k => $v) {
            $info = getDatas('sale_payreg',['*'],['id'=>$v]);
            // dump($v);die;
            if(!empty($info)){
                switch ($info[0]['paytype_id']) {
                    case 2:
                        if($type == 'update'){
                            updateData('voucher',['sale_payreg_id'=>$v],['sale_payreg_id'=>0,'sale_id'=>0]);
                        }else{
                            deleteData('voucher',['sale_payreg_id'=>$v],$v);
                        }
                        
                        // updateData('sale_payreg',['id'=>$v],['del_at'=>time(),'del_id'=>$this->user_id]);
                        break;
                    case 3:
                    case 4:
                        if($type == 'update'){
                            updateData('sale_pay_cheque',['sale_payreg_id'=>$v],['del_at'=>time(),'del_id'=>$this->user_id]); 
                        }else{
                            deleteData('sale_pay_cheque',['sale_payreg_id'=>$v],$v);
                        }   
                        // updateData('sale_payreg',['id'=>$v],['del_at'=>time(),'del_id'=>$this->user_id]);
                        break;
                        
                    case 5:
                        if($type == 'update'){
                            updateData('sale_pay_transfer',['sale_payreg_id'=>$v],['del_at'=>time(),'del_id'=>$this->user_id]);
                        }else{
                            deleteData('sale_pay_transfer',['sale_payreg_id'=>$v],$v);
                        }
                        break;
                    default:
                        // $this->deldata('update',$table,$v);
                        if($type == 'update'){
                            Db::name($table)->where(['id'=>$v])->update(['del_at'=>time(),'del_id'=>$this->user_id]);
                        }else{
                            deleteData('sale_pay_cheque',['sale_payreg_id'=>$v],$v);
                        }
                        break;
                }
                if($type == 'update'){
                    $res1 = updateData('sale_payreg',['id'=>$v],['del_at'=>time(),'del_id'=>$this->user_id]);
                }else{
                    deleteData('sale_pay_index',['sale_payreg_id'=>$v]);
                    deleteData('sale_payreg',['id'=>$v]);
                }
            }
        }
        // $res = deleteData('update',$table,'1=1',$data);
    }

    function checkDetail()
    {
        if(isset($this->data['requestType']) && $this->data['requestType'] == 'detail'){

            $returnData =  $this->getSaleDetail('checkDetail') ;
            $returnData['data']['saleList']['company_name'] = getValue('company',['id'=>$returnData['data']['saleList']['co_id']],'name');
            $returnData['data']['saleList']['branchcompany_name'] = getValue('co_branch',['id'=>$returnData['data']['saleList']['co_branch_id']],'name');
            $returnData['data']['saleList']['address'] = $returnData['data']['saleList']['branchcompany_name'] ? getValue('co_branch',['id'=>$returnData['data']['saleList']['co_branch_id']],'addr') : getValue('co_profile',['co_id'=>$returnData['data']['saleList']['co_id']],'addr');
            $returnData['data']['saleList']['create_name'] = getValue('admin',['id'=>$returnData['data']['saleList']['create_id']],'nickname');
            $returnData['data']['saleList']['create_time'] = getTimeDates($returnData['data']['saleList']['create_at'],$this->lang);
            $returnData['data']['saleList']['update_name'] = getValue('admin',['id'=>$returnData['data']['saleList']['update_id']],'nickname');
            $returnData['data']['saleList']['update_time'] = getTimeDates($returnData['data']['saleList']['update_at'],$this->lang);
            $delivery_typeMkey = getValue('sale_delivery_type',['id'=>$returnData['data']['saleList']['delivery_type_id']],'mkey');
            $returnData['data']['saleList']['delivery_type_name'] = getValue('multi_lang',['mkey'=>$delivery_typeMkey,'lang'=>$this->lang],'content');

            $returnData['data']['saleList']['trans_name'] = $returnData['data']['saleList']['trans_id'] ? getValue('company',['id'=>$returnData['data']['saleList']['trans_id']],'name') : '';
            $returnData['data']['saleList']['saler_name'] = getValue('admin',['id'=>$returnData['data']['saleList']['saler_id']],'nickname');

            
            if(!empty($returnData['data']['payregList'])){
                $payregList = $returnData['data']['payregList']; 
                foreach ($payregList as $k => $v) {
                    if(!empty($v['payregDetail'])){
                        if($v['paytype_id'] == 5){
                            // 转账存入账号信息
                            $transferInDetail = Db::name('accounts')->where(['id'=>$v['payregDetail'][0]['transferInId']])->find();
                            $payregList[$k]['payregDetail'][0]['transferInBrankName'] = $transferInDetail['bankname'];
                            $payregList[$k]['payregDetail'][0]['transferInAccountName'] = $transferInDetail['account_name'];

                            // 转账转出账号信息
                            if($v['payregDetail'][0]['transferOutId']){
                                $transferOut = Db::name('co_bank')->where(['id'=>$v['payregDetail'][0]['transferOutId']])->find();
                                $payregList[$k]['payregDetail'][0]['transferOutBrankName'] = $transferOut['bankname'];
                                $payregList[$k]['payregDetail'][0]['transferOutAccountName'] = $transferOut['account_name'];    
                            }else{
                                $payregList[$k]['payregDetail'][0]['transferOutBrankName'] = '';
                                $payregList[$k]['payregDetail'][0]['transferOutAccountName'] = '';  
                            }

                            $payregList[$k]['payregDetail'][0]['checkName'] = $v['payregDetail'][0]['check_id'] ? getValue('admin',['id'=>$v['payregDetail'][0]['check_id']],'nickname') : '-';
                            $payregList[$k]['payregDetail'][0]['checkTime'] = $v['payregDetail'][0]['success_at'] ? getTimeDates($v['payregDetail'][0]['success_at'],$this->lang) :'';
                        }

                        if($v['paytype_id'] == 3 || $v['paytype_id'] == 4){
                            $payregList[$k]['payregDetail'][0]['got_name'] = $v['payregDetail'][0]['got_id'] ? getValue('admin',['id'=>$v['payregDetail'][0]['got_id']],'nickname') : '-';
                            $payregList[$k]['payregDetail'][0]['got_time'] = $v['payregDetail'][0]['got_at'] ? getTimeDates($v['payregDetail'][0]['got_at'],$this->lang) :'';

                            $payregList[$k]['payregDetail'][0]['checkName'] = $v['payregDetail'][0]['check_id'] ? getValue('admin',['id'=>$v['payregDetail'][0]['check_id']],'nickname') : '-';
                            $payregList[$k]['payregDetail'][0]['checkTime'] = $v['payregDetail'][0]['success_at'] ? getTimeDates($v['payregDetail'][0]['success_at'],$this->lang) :'';

                            $payregList[$k]['payregDetail'][0]['remark'] = '';
                        }

                        if($v['paytype_id'] == 6){
                            // 存入账号信息
                            $transferInDetail = Db::name('accounts')->where(['id'=>$v['payregDetail'][0]['account_id']])->find();
                            $payregList[$k]['payregDetail'][0]['brankName'] = $transferInDetail['bankname'];
                            $payregList[$k]['payregDetail'][0]['accountName'] = $transferInDetail['account_name'];
                            $payregList[$k]['payregDetail'][0]['accountNum'] = $transferInDetail['account_num'];
                        }
                    }    
                }
                $returnData['data']['payregList'] = $payregList;
            }


            $saleMakeDetail['status'] = $this->getsaleStatus($returnData['data']['saleList']); 
            // 配货主管
            $sale_make = Db::name('sale_make')->where(['sale_id'=>$returnData['data']['saleList']['id']])->find();
            $saleMakeDetail['saleMakeName'] = !empty($sale_make) ? getValue('admin',['id'=>$sale_make['create_id']],'nickname') : '-';
            $saleMakeDetail['checkerName'] = !empty($sale_make) ? getValue('admin',['id'=>$sale_make['checker_id']],'nickname') : '-';
            $saleMakeDetail['checkerTime'] = getTimeDates($sale_make['create_at'],$this->lang);
            $saleMakeDetail['print_count'] = !empty($sale_make) ? $sale_make['print_count'] : '-';
            $saleMakeDetail['print_time'] = getTimeDates($sale_make['print_at'],$this->lang);

            // 仓管员
            $pickup_id = getValue('make_pickup_detail',['sale_id'=>$returnData['data']['saleList']['id'],'pickup_id'=>['gt',0]],'pickup_id');
            if($pickup_id){
                $make_pickup = Db::name('make_pickup')->where(['id'=>$pickup_id])->find();
            }else{
                $make_pickup = [];
            }
            $saleMakeDetail['pickupName'] = !empty($make_pickup) ? getValue('admin',['id'=>$make_pickup['create_id']],'nickname') : '';
            $saleMakeDetail['pickupTime'] = !empty($make_pickup) ? getTimeDates($make_pickup['create_at'],$this->lang) : '';

            //包装主管
            $process_id = getValue('make_process_detail',['sale_id'=>$returnData['data']['saleList']['id'],'process_id'=>['gt',0]],'process_id');
            if($process_id){
                $make_process = Db::name('make_process')->where(['id'=>$process_id])->find();
            }else{
                $make_process = [];
            }
            $saleMakeDetail['processName'] = !empty($make_process) ? getValue('admin',['id'=>$make_process['create_id']],'nickname') : '';
            $saleMakeDetail['processTime'] = !empty($make_process) ? getTimeDates($make_process['create_at'],$this->lang) : '';

            //装箱员
            $sale_pack = Db::name('sale_pack')->where(['sale_id'=>$returnData['data']['saleList']['id']])->find();
            $saleMakeDetail['packName'] = !empty($sale_pack) ? getValue('admin',['id'=>$sale_pack['create_id']],'nickname') : '';
            $saleMakeDetail['packTime'] = !empty($sale_pack) ? getTimeDates($sale_pack['create_at'],$this->lang) : '';

            //开票员
            $sale_invoice = Db::name('sale_invoice')->where(['sale_id'=>$returnData['data']['saleList']['id']])->find();
            $saleMakeDetail['invoiceName'] = !empty($sale_invoice) ? getValue('admin',['id'=>$sale_invoice['drawer_id']],'nickname') : '';
            $saleMakeDetail['invoiceTime'] = !empty($sale_invoice) ? getTimeDates($sale_invoice['drawer_at'],$this->lang) : '';

            $returnData['data']['saleList']['sale_invoice_no'] = $sale_invoice['number'];
            $returnData['data']['saleList']['sale_invoice_type'] = getValue('sale_invoice_type',['id'=>$sale_invoice['invoice_type_id']],'code');
            $returnData['data']['saleList']['drawer_name'] = $saleMakeDetail['invoiceName'];
            $returnData['data']['saleList']['drawer_time'] = $saleMakeDetail['invoiceTime'];

            //银行单
            $sale_pay_bill = Db::name('sale_pay_bill')->where(['sale_id'=>$returnData['data']['saleList']['id']])->find();
            $saleMakeDetail['billName'] = !empty($sale_pay_bill) ? getValue('admin',['id'=>$sale_pay_bill['drawer_id']],'nickname') : '';
            $saleMakeDetail['billTime'] = !empty($sale_pay_bill) ? getTimeDates($sale_pay_bill['drawer_at'],$this->lang) : '';

            // 装箱单
            $Sale_pack = new Sale_pack();
            $saleMakeDetail['salePackData'] = $Sale_pack->getprodata($returnData['data']['saleList']['id'],$this->lang);

            // 物流主管
            if($returnData['data']['saleList']['delivery_type_id'] == 4){
                $make_delivery = Db::name('make_logistics')->where(['sale_id'=>$returnData['data']['saleList']['id']])->find();
                $saleMakeDetail['isreceipt'] = '-';
            }else{
                $make_delivery_detail = Db::name('make_delivery_detail')->where(['sale_id'=>$returnData['data']['saleList']['id']])->find();
                $make_delivery = Db::name('make_delivery')->where(['id'=>$make_delivery_detail['delivery_id']])->find();
                $saleMakeDetail['isreceipt'] = $make_delivery_detail['receipt'] ? 'O' : '-';
            }
            $saleMakeDetail['make_deliveryName'] = !empty($make_delivery) ? getValue('admin',['id'=>$make_delivery['create_id']],'nickname') : '';
            $saleMakeDetail['make_deliveryTime'] = !empty($make_delivery) ? getTimeDates($make_delivery['create_at'],$this->lang) : '';
            


            $returnData['data']['saleMakeDetail'] = $saleMakeDetail;
            // dump($returnData);die;
            return json_encode($returnData);
        }else{
            return view('checkdetail',['id'=>$this->data['id']]);
        }
        
    }

    function getSaleDetail($type)
    {
        if($this->data['id']){

            $returnData['saleList'] = db::name('sale')->where(['id'=>$this->data['id']])->find();
            if(empty($returnData['saleList'])) return json_encode(array('status'=>2,'msg'=>'请选择正确的销售订单'));
            $returnData['saleList']['create_time'] = getTimeDates($returnData['saleList']['create_at'],$this->lang,true);
            $returnData['invoiceTypeId'] = getValue('sale_invoice',['sale_id'=>$this->data['id']],'invoice_type_id');

            if($type == 'edit'){
                // 送货方式
                $returnData['saleDeliveryTypeList'] = getSearch('sale_delivery_type','zu',['zu.id,mu.content'],['mu.lang'=>$this->lang],[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id desc');

                // 费用类型
                $returnData['saleCostType'] = getDatas('sale_cost_type',['id,name,options']);

                // 付款方式
                $returnData['salePayType'] = [];
                $salePayType = $this->getCoSale($returnData['saleList']['co_id'],0);
                if($salePayType) $returnData['salePayType'] = $salePayType['salePayType'];

                // 产品分类
                $returnData['proType'] = getSearch('procat','zu',['zu.id,zu.pid,mu.content'],['mu.lang'=>$this->lang],[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id desc');
                $returnData['proType'] = getTree($returnData['proType']);

                // 产品分类
                $proCate = getSearch('procat','zu',['zu.id,zu.pid,mu.content'],['mu.lang'=>$this->lang],[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id desc');
                $returnData['proCate'] = getTree($proCate);

                // 收款账号
                $returnData['receivingAccount'] = $this->accounts();

                // 付款安排快捷输入
                $returnData['quickInput'] = $this->getquickInput();

                $returnData['company'] = getDatas('company',['id','name']);

                $returnData['branchCompany'] = getDatas('co_branch',['id','name'],['co_id'=>$returnData['saleList']['co_id']]);

                if($returnData['branchCompany']){
                    $returnData['companyInfo'] = $this->getCompanyDetail($returnData['branchCompany'][0]['id'],'branch');
                }else{
                    $returnData['companyInfo'] = $this->getCompanyDetail($returnData['company'][0]['id'],'main');
                }
                
                $returnData['logisticsCompany'] = getDatas('company',['id,name'],['type_id'=>4]);
                $returnData['saler'] = $this->getSalerList($returnData['saleList']['saler_id']);
            }

            // 订单备注
            $saleOrderRemarkData= getDatas('sale_remark',['*,remark content'],['sale_id'=>$this->data['id'],'sale_detail_id'=>0]);
            if(!empty($saleOrderRemarkData)){
                foreach ($saleOrderRemarkData as $k => $v) {
                    $returnData['saleOrderRemarkData'][$k] = $v;
                    $returnData['saleOrderRemarkData'][$k]['create_at'] = date("Y-m-d H:i:s",$v['create_at']); 
                    $returnData['saleOrderRemarkData'][$k]['create_name'] = getValue('admin',['id'=>$v['create_id']],'nickname'); 
                }
            }else{
                $returnData['saleOrderRemarkData'] = [];
            }
            
            // 产品明细
            $returnData['orderList'] = $this->getorderList($this->data['id']);

            // 费用
            $returnData['costData'] = $this->getcostData($this->data['id']);

            // 付款安排
            $returnData['paymentList'] = $this->getpaymentList($this->data['id'],($returnData['saleList']['pay'] + $returnData['saleList']['cost']) );

            // 付款登记
            $returnData['payregList'] = $this->payreg($this->data['id']);

            // 送货单 
            $returnData['deliveryNoteList'] = $this->deliveryNote($this->data['id']);

            // 订单记录
            $returnData['saleLog'] = $this->getSaleLog($this->data['id']);

            // dump($returnData['paymentList']);die;
            return array('status'=>1,'data'=>$returnData);
        }
    }

    public function saleEdit()
    {
        if(isset($this->data['request']) && $this->data['request'] == 'update'){

            // dump($this->data);die;
            $noticeText = noticeText( $this->data,['data'=>'完善订单数据','orderList'=>'完善产品数据','paymentList'=>'完善付款安排数据'],'','isset');
            if($noticeText['status'] == 2) return json_encode(array('status'=>2,'msg'=>'编辑失败:'.$noticeText['msg']));
            $noticeText = noticeText( $this->data['data'],['companyId'=>'客户','saler_id'=>'业务员','saleDeliveryTypeId'=>'送货方式']);
            if($noticeText['status'] == 2) return json_encode(array('status'=>2,'msg'=>'编辑失败:'.$noticeText['msg']));
           
            $res = $this->implementSaleSql('update',$this->data['data']);

            if(isset($this->data['saleOrderRemarkData']))
                $res1 = $this->implementSaleRemark('update',$this->data['saleOrderRemarkData'],$this->data['data']['saleOrderNo']);
            
            $res2 = $this->implementSaleDetail('update',$this->data['orderList'],$this->data['data']['saleOrderNo']);

            if(isset($this->data['costData']))
                $res3 = $this->implementSaleCostDetail('update',$this->data['costData'],$this->data['data']['saleOrderNo']);

            $res4 = $this->implementSalePayPlanDetail('update',$this->data['paymentList'],$this->data['data']['saleOrderNo']);

            if(isset($this->data['payregList']))
                $res5 = $this->implementSalePayregDetail($this->data['payregList'],$this->data['data']['saleOrderNo']);
            
            // if(isset($this->data['deliveryNoteList']))
            //     $res6 = $this->implementDeliveryNote($this->data['deliveryNoteList'],$this->data['data']['saleOrderNo'],$this->data['data']['saleDeliveryTypeId']);

            if(isset($this->data['delList']))
                $res6 = $this->delList($this->data['delList'],$this->data['data']['saleOrderNo']);

            if(isset($this->data['clearList']))
                $res6 = $this->clearList($this->data['clearList'],$this->data['data']['saleOrderNo']);

            return json_encode(array('status'=>1,'msg'=>'编辑成功'));
            
            
        }else if(isset($this->data['request']) && $this->data['request'] == 'edit'){
            return json_encode($this->getSaleDetail('edit'));

        }else if(isset($this->data['request']) && $this->data['request'] == 'status'){
            return json_encode($this->proStoreStatus($this->data['pro_id'],$this->data['prochar_id'],$this->data['prochar_qty']));

        }else if(isset($this->data['request']) && $this->data['request'] == 'storeType'){
            return json_encode($this->isNormalSaleOrder($this->data['pro_id'],$this->data['prochar_id'],$this->data['prochar_qty']));

        }else if(isset($this->data['request']) && $this->data['request'] == 'invoiceType'){ // 获取发票类型
            // dump(321);
            return json_encode($this->getInvoiceType());

        }else if(isset($this->data['request']) && $this->data['request'] == 'saleRecording'){ // 获取发票类型
            // dump(321);
            return json_encode($this->getSaleRecording());

        }else{
            // dump($this->data['id']);die;
            $tab = isset($this->data['tab']) ? $this->data['tab'] : '';
            return view('saleopen',['title'=>'编辑销售订单','edit_id'=>$this->data['id'],'requestType'=>'edit','create_id'=>$this->user_id,'create_name'=>session('admin')['nickname'],'tab'=>$tab]);
        }
    }

    function getSaleRecording()
    {
        // dump($this->data);die;
        $res = [];
        if(isset($this->data['pro_id']) && isset($this->data['prochar_id'])){
            $where['zu.pro_id'] = $this->data['pro_id'];
            $where['zu.prochar_id'] = $this->data['prochar_id'];
            $where['s.co_id'] = $this->data['company_id'];
            $where['s.co_branch_id'] = $this->data['co_branch_id'];

            $res = Db::name('sale_detail')
                        ->alias('zu')
                        ->join([['sale s','zu.sale_id = s.id']])
                        ->field(['zu.price,zu.qty,zu.sale_id,s.finish_at'])
                        ->where($where)
                        ->limit(3)
                        ->order('zu.id desc')
                        ->select();
            foreach ($res as $k => $v) {
                $res[$k]['finish_at'] = getTimeDates($v['finish_at'],$this->lang,true);
            }

        }
        // dump($res);die;
        return $res;
    }

    // 查找攻速信息 和公司分公司信息
    function searchCompany()
    {
        if(isset($this->data['request']) && $this->data['request'] == 'company'){
            if(isset($this->data['searchCompany'])){
                $where['id|name'] = ['like','%'.$this->data['searchCompany'].'%'];
                $where['type_id'] = 2; // 经销商
                // $where['saler_id'] = $this->user_id; // 当前登录ID
                // if(授权)  可以查看下级得客户信息
                // $position_id = getValue('admin',['id'=>$this->user_id],'position_id');
                // $position_ids = getTreeChild(false,'position','1=1',$this->lang,$position_id);
                // $companyAdmin_ids = '';
                // foreach ($position_ids as $k => $v) {
                //     $admin_ids = getDatas('admin',['id'],['position_id'=>$v['id']]);
                //     foreach ($admin_ids as $k1 => $v1) {
                //         $companyAdmin_ids .= $v1['id'].',';
                //     }
                // }
                // $companyAdmin_ids = rtrim($companyAdmin_ids,',');
                // $where['saler_id'] = ['in',$companyAdmin_ids];

                $company = getDatas('company',['id,name'],$where,'id desc','1,10');
            }else{
                $company = [];
            }
            return json_encode(array('status'=>1,'data'=>$company));
        // 获取分公司
        }else if(isset($this->data['request']) && $this->data['request'] == 'branch'){
            if(isset($this->data['company_id']) && $this->data['company_id']){
                $branch = getDatas('co_branch',['id,name'],['co_id'=>$this->data['company_id']]);
                $companyInfo = $this->getCompanyDetail($this->data['company_id'],'main');
                $saler = $this->getSalerList($companyInfo['data']['saler_id']);
                // $saleRecording = $this->getSaleRecording($this->data['company_id']);
            }else{
                $branch = [];
                $companyInfo = [];
                $saler = [];
            }
            return json_encode(array('status'=>1,'data'=>['branch'=>$branch,'companyInfo'=>$companyInfo,'saler'=>$saler]));
        }else if(isset($this->data['request']) && $this->data['request'] == 'wuliu'){
            $where['type_id'] = 4; // 物流公司
            $wuliu = getDatas('company',['id,name'],$where);
            return json_encode(array('status'=>1,'data'=>$wuliu));
        }else if(isset($this->data['request']) && $this->data['request'] == 'detail'){
            if(isset($this->data['company_id']) && $this->data['company_id']){

                $companyInfo = $this->getCompanyDetail($this->data['company_id'],'branch');
            }else{
                $companyInfo = [];
            }
            return json_encode(array('status'=>1,'data'=>$companyInfo));
        }
        
    }

    // 获取业务员
    function getSalerList($saler_id)
    {
        $saler = getDatas('admin',['id,nickname'],['id'=>$saler_id]);
        if(empty($saler)){
            $saler = getDatas('admin',['id,nickname'],['position_id'=>15]);
        }
        return $saler;
    }

    // 获取公司详情
    function getCompanyDetail($company_id,$type)
    {
        $data['status'] = 'detail';
        $data['company_id'] = $company_id;
        $data['lang'] = $this->lang;
        if($type == 'main'){
            $companyInfo = model('company')->getdetail($data);
            $where['co_id'] = $company_id;
            $companyInfo['coSale'] = $this->getCoSale($company_id,0);
        }else{
            $companyInfo = getDatas('co_branch',['id,name'],['id'=>$company_id]);;
            $where['branch_id'] = $company_id;
            $companyInfo['coSale'] = $this->getCoSale(0,$company_id);
        } 
        $co_sale = getDatas('co_sale',['credit,level,co_id'],$where);
        $companyInfo['data']['credit'] = empty($co_sale) ? 0 : $co_sale[0]['credit'];
        $companyInfo['data']['level'] = empty($co_sale) ? 0 : $co_sale[0]['level'];
        // dump($companyInfo);die;    
        return $companyInfo;
    }

    // 获取产品信息
    function getProInfo()
    {   
        $returnData = [];
        if(isset($this->data['proCateId']) && $this->data['proCateId']) $data['procat_id'] = $this->data['proCateId'];
        if(isset($this->data['searchText']) && $this->data['searchText']) $data['searchText'] = $this->data['searchText'];
        
        if(isset($data)){
            $proList = getProList($data,$this->lang);
            // dump($proList);die;
            if(!empty($proList)){
                foreach ($proList as $k => $v) {
                    $returnData[$k] = getFeature($v['pro_id'],$this->lang,$v['id']);
                    $returnData[$k]['img_url'] = getImgUrl($returnData[$k]['pro_id'], 48, $type = 'prochar', $returnData[$k]['prochar_id']);
                    $returnData[$k]['package_qty'] = $v['package_qty'];
                    $returnData[$k]['prochar_qty'] = $v['qty'];
                    $returnData[$k]['ctn_size'] = $v['ctn_size'];
                    $returnData[$k]['ctn_m3'] = $v['ctn_m3'];
                    $returnData[$k]['ctn_kgs'] = $v['ctn_kgs'];
                    $returnData[$k]['storeData'] = Db::name('store')->where(['pro_id'=>$v['pro_id'],'prochar_id'=>$returnData[$k]['prochar_id']])->sum('qty'); 
                    $proPriceAndDis = $this->getLowestPriceAndDis($v['pro_id'],$v['id']);
                    $returnData[$k]['lowest_price'] = $proPriceAndDis['lowest_price'];
                    $returnData[$k]['lowest_discount'] = $proPriceAndDis['lowest_discount'];
                }
            }
        }
        // dump($returnData);die;
        return json_encode(array('status'=>1,'data'=>$returnData));
    }

    // 获取产品的最低价格和最高折扣
    function getLowestPriceAndDis($pro_id,$prochar_id)
    {
        // 获取当前操作人员的职务
        $position_id = session('admin')['position_id'];

        // 管理员和CEO  不限制
        if($position_id == 1 || $position_id == 2){
            $return['lowest_price'] = 0;
            $return['lowest_discount'] = 100000000;
        }else{
            // 根据职务获取价格分类，职务一对多 价格分类
            $sql = "SELECT id FROM nt_price_type WHERE FIND_IN_SET(".$position_id.",position_ids)";
            $priceTypeIds = Db::query($sql);
            $priceTypeIds = implode( array_column($priceTypeIds, 'id'), ',');

            $where['zu.price_type_id'] = ['in',$priceTypeIds];
            $where['p.pro_id'] = $pro_id;
            $where['p.prochar_id'] = $prochar_id;

            $join = [['price p','zu.price_id = p.id']];

            // 最低价格
            $return['lowest_price'] = Db::name('price_value')
                                        ->alias('zu')
                                        ->join($join)
                                        ->where($where)
                                        ->min('amount');

            // 价格分类中对应产品的最低折扣
            $lowest_discount = Db::name('price_value')
                                ->alias('zu')
                                ->join($join)
                                ->where($where)
                                ->min('discount_range');

            // 职务折扣
            $position_discount = getValue('price_discount',['position_id'=>$position_id],'range');

            // 产品允许最高折扣是 价格分类的最低折扣和职务折扣 两者中取小的
            $return['lowest_discount'] = $lowest_discount > $position_discount ? $position_discount : $lowest_discount;
            $return['lowest_discount'] = $return['lowest_discount'] ? $return['lowest_discount'] : 0;
        }
        // dump($return);die;
        return $return;

    }

    // 付款登记
    function payreg($id)
    {
        $join = [
                ['sale_payreg p','zu.sale_payreg_id = p.id',"LEFT"],
                ['sale_pay_type pt','p.paytype_id = pt.id',"LEFT"],
                ['multi_lang ptn','pt.mkey = ptn.mkey',"LEFT"]
            ];
        //  'p.paytype_id'=>['neq',6]  支付方式为银行单的 不显示出来，在开票员操作时，操作银行单的登记数据
        $res = getSearch('sale_pay_index','zu',['zu.sale_id,zu.sale_payplan_id,p.*,ptn.content paytype_name'],['zu.sale_id'=>$id,'ptn.lang'=>$this->lang,'p.paytype_id'=>['neq',6]],$join,'zu.id desc');
        foreach ($res as $k => $v) {
            $res[$k]['create_name'] = getValue('admin',['id'=>$v['create_id']],'nickname'); 
            $res[$k]['create_at'] = getTimeDates($v['create_at'],$this->lang,true);

            $res[$k]['check_name'] = getValue('admin',['id'=>$v['check_id']],'nickname'); 
            $res[$k]['check_time'] = $v['success_at'] ? getTimeDates($v['success_at'],$this->lang,true) : '';
            $res[$k]['pay_day'] = $v['pay_day'] ? getTimeDates($v['pay_day'],$this->lang,true) : '';
            if($v['success_at']) $res[$k]['status'] = 1;//'完成';
            if($v['fail_at']) $res[$k]['status'] = 2;//'失败';
            if($v['paid'] == $v['amount']) $res[$k]['status'] = 3;//'收到';
            if(!$v['check_id'] && !$v['success_at'] && !$v['fail_at'] && $v['paid'] != $v['amount']) $res[$k]['status'] = 4 ;//'确认中';

            $res[$k]['payregDetail'] = [];
            if($v['paytype_id'] == 2){
                $res[$k]['payregDetail'] = getDatas('voucher',['*'],['sale_payreg_id'=>$v['id']]);

            } else if($v['paytype_id'] == 3 || $v['paytype_id'] == 4){
                $res[$k]['payregDetail'] = getDatas('sale_pay_cheque',['*,number chequeNo,signature chequeSignature,pay_day,amount chequePrice,scan_url chequeScan_url,bank_id'],['sale_payreg_id'=>$v['id']]);
                    $res[$k]['pay_day'] = $res[$k]['payregDetail'][0]['chequeDay'] = getTimeDates($res[$k]['payregDetail'][0]['pay_day'],$this->lang,true);
                if(!empty($res[$k]['payregDetail'])){
                    $res[$k]['payregDetail'][0]['bank_name'] = getValue('co_bank',['id'=>$res[$k]['payregDetail'][0]['bank_id']],'bankname');
                }
            } else if($v['paytype_id'] == 5){
                $res[$k]['payregDetail'] = getDatas('sale_pay_transfer',['*'],['sale_payreg_id'=>$v['id']]);
                if(!empty($res[$k]['payregDetail'])){
                    $res[$k]['payregDetail'][0]['transferOutId'] = $res[$k]['payregDetail'][0]['co_bank_id'];
                    $res[$k]['payregDetail'][0]['transferOutName'] = getValue('co_bank',['id'=>$res[$k]['payregDetail'][0]['co_bank_id']],'account_num');
                    $res[$k]['payregDetail'][0]['transferInId'] = $res[$k]['payregDetail'][0]['account_id'];
                    $res[$k]['payregDetail'][0]['transferInName'] = getValue('accounts',['id'=>$res[$k]['payregDetail'][0]['account_id']],'account_num');

                    $res[$k]['pay_day'] = $res[$k]['payregDetail'][0]['transferDay'] = getTimeDates($res[$k]['payregDetail'][0]['pay_day'],$this->lang,true);
                    $res[$k]['payregDetail'][0]['transferPrice'] = $res[$k]['payregDetail'][0]['amount'];
                    $res[$k]['payregDetail'][0]['transferNo'] = $res[$k]['payregDetail'][0]['number'];
                    // $res[$k]['payregDetail'][0]['scan_url'] = $res[$k]['payregDetail'][0]['scan_url'];
                }
            } else if($v['paytype_id'] == 6){
                $res[$k]['payregDetail'] = getDatas('sale_pay_bill',['*'],['sale_payreg_id'=>$v['id']]);
                if(!empty($res[$k]['payregDetail'])){
                    $res[$k]['pay_day'] = $res[$k]['payregDetail'][0]['transferDay'] = getTimeDates($res[$k]['payregDetail'][0]['pay_day'],$this->lang,true);

                    $res[$k]['payregDetail'][0]['create_name'] = $res[$k]['payregDetail'][0]['check_id'] ? getValue('admin',['id'=>$res[$k]['payregDetail'][0]['create_id']],'nickname') :'-';
                    $res[$k]['payregDetail'][0]['create_time'] = $res[$k]['payregDetail'][0]['create_at'] ? getTimeDates($res[$k]['payregDetail'][0]['create_at'],$this->lang) : '';

                    $res[$k]['payregDetail'][0]['check_name'] = $res[$k]['payregDetail'][0]['check_id'] ? getValue('admin',['id'=>$res[$k]['payregDetail'][0]['check_id']],'nickname'):'-';
                    $res[$k]['payregDetail'][0]['check_time'] = $res[$k]['payregDetail'][0]['success_at'] ? getTimeDates($res[$k]['payregDetail'][0]['success_at'],$this->lang) : '';
                }
            }
            
                // dump($res[$k]['payregDetail']);die;
            // 
        }
        // dump($res);die;
        return $res;
    }

    function getorderList($id){
        $res = getDatas('sale_detail',['*'],['sale_id'=>$id]);
        $saleInfo = getDatas('sale',['co_id,co_branch_id,warehouse_id'],['id'=>$id]);
        if(!empty($saleInfo)){
            $future = getSearch('future','zu',['zu.*,fd.*'],['zu.co_id'=>$saleInfo[0]['co_id'],'zu.co_branch_id'=>$saleInfo[0]['co_branch_id']],[['future_detail fd','zu.id = fd.future_id']],'zu.id desc');
            foreach ($future as $k => $v) {
                $v['discount'] = 0;
                $v['commission'] = 0;
                array_push($res, $v);
            }
        }
        foreach ($res as $k1 => $v1) {
            $res[$k1]['pro_name'] = getValue('multi_lang',['mkey'=>'pro_'.$v1['pro_id'],'lang'=>$this->lang],'content');
            $res[$k1]['model'] = getValue('prochar',['id'=>$v1['prochar_id']],'model');

            $res[$k1]['package_qty'] = getValue('prochar',['id'=>$v1['prochar_id']],'package_qty');
            $res[$k1]['prochar_qty'] = getValue('prochar',['id'=>$v1['prochar_id']],'qty');
            $res[$k1]['ctn_size'] = getValue('prochar',['id'=>$v1['prochar_id']],'ctn_size');
            $res[$k1]['ctn_m3'] = getValue('prochar',['id'=>$v1['prochar_id']],'ctn_m3');
            $res[$k1]['ctn_kgs'] = getValue('prochar',['id'=>$v1['prochar_id']],'ctn_kgs');
            
            $res[$k1]['status'] = $this->proStoreStatus($v1['pro_id'],$v1['prochar_id'],$res[$k1]['prochar_qty']);
            $res[$k1]['storeType'] = $this->isNormalSaleOrder($v1['pro_id'],$v1['prochar_id'],$v1['qty']);     // 期货、外调

            $res[$k1]['storeType_subWarehouseQty'] = getValue('store',['pro_id'=>$v1['pro_id'],'prochar_id'=>$v1['prochar_id'],'warehouse_id'=>$saleInfo[0]['warehouse_id']],'qty');
            $res[$k1]['storeType_storeQty'] = getValue('store',['pro_id'=>$v1['pro_id'],'prochar_id'=>$v1['prochar_id']],'qty');
            $res[$k1]['sale_qty_1y'] = $this->getProSale($v1['pro_id'],$v1['prochar_id'],'sale_qty_1y');

            $res[$k1]['img_url'] = getImgUrl($v1['pro_id'], 48, $type = 'prochar', $v1['prochar_id']);
            $res[$k1]['orderNum'] = $v1['qty'];
            $res[$k1]['orderPrice'] = $v1['price'];
            $res[$k1]['Subtotal'] = $v1['qty'] * $v1['price'];
            $res[$k1]['orderListDiscount'] = (int)$v1['discount'] > 0 ? abs($v1['discount']) : abs($v1['discount']);
            $res[$k1]['discountType'] = (int)$v1['discount'] > 0 ? 'BRL' : '%';
            $res[$k1]['orderListCommission'] = isset( $v1['commission'] ) ? $v1['commission'] : 0;
            $res[$k1]['commissionPrice'] = isset($v1['commission']) ? abs($v1['commission'])/100*($v1['qty'] * $v1['price']) : 0;
            $res[$k1]['discount'] = isset( $v1['discount'] ) ? abs($v1['discount']) :0 ;
            $res[$k1]['orderListDiscountPriceSum'] = (int)$v1['discount'] > 0 ? abs($v1['discount']) : abs($v1['discount'])/100*($v1['qty'] * $v1['price']);
            $res[$k1]['discountPriceSum'] = (int)$v1['discount'] > 0 ? abs($v1['discount']) : abs($v1['discount'])/100*($v1['qty'] * $v1['price']);
            $res[$k1]['remarksList'] = getDatas('sale_remark',['*,remark content'],['sale_id'=>$id,'sale_detail_id'=>$v1['id']]);
        }
        // dump($res);die;
        return $res;
    }

    function getcostData($id)
    {
        $res = getDatas('sale_cost',['*,cost_type_id saleCostTypeId,amount costPrice'],['sale_id'=>$id]);
        foreach ($res as $k => $v) {
            $res[$k]['create_at'] = date("Y-m-d H:i:s",$v['create_at']);
            $res[$k]['create_name'] = getValue('admin',['id'=>$v['create_id']],'nickname');
            $res[$k]['costRemarks'] = getValue('sale_cost_remark',['sale_id'=>$v['sale_id'],'sale_cost_id'=>$v['id']],'remark');
            $res[$k]['content'] = getValue('sale_cost_type',['id'=>$v['saleCostTypeId']],'name');
        }
        return $res;
    }

    // 送货单
    function deliveryNote($sale_id)
    {
        $field = ['zu.*,dm.content delivery_type_name,c.name company_name,cb.name branch_name,it.code sale_invoice_code'];
        $where['zu.sale_id'] = $sale_id;
        $where['dm.lang'] = $this->lang;
        $where['dm.lang'] = $this->lang;
        // $where['r.detail_id'] = 0;
        $join = [
                    ['sale_delivery_type d','zu.delivery_type_id = d.id'],
                    ['multi_lang dm','d.mkey = dm.mkey',"LEFT"],
                    ['company c','zu.co_id = c.id'],
                    ['co_branch cb','zu.co_branch_id = cb.id','LEFT'],
                    // ['delivery_note_remark r','zu.id = r.delivery_note_id','LEFT'],
                    ['sale_invoice i','zu.id = i.delivery_note_id','LEFT'],
                    ['sale_invoice_type it','i.invoice_type_id = it.id','LEFT'],
                ];
        $data = getSearch('delivery_note','zu',$field,$where,$join,'zu.id desc');
        // dump($data);die;
        if(!empty($data)){
            foreach ($data as $k => $v) {
                $data[$k]['remark'] = getValue('delivery_note_remark',['delivery_note_id'=>$v['id'],'detail_id'=>0],'remark');
                $data[$k]['branch_name'] = $data[$k]['branch_name'] ? $data[$k]['branch_name'] : '';
                $data[$k]['sale_invoice_code'] = $data[$k]['sale_invoice_code'] ? $data[$k]['sale_invoice_code'] : '-';

                $data[$k]['create_name'] = getValue('admin',['id'=>$v['create_id']],'nickname');
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_at']);
                $data[$k]['update_name'] = getValue('admin',['id'=>$v['update_id']],'nickname');
                $data[$k]['update_time'] = date('Y-m-d H:i:s',$v['update_at']);

                // 送货单详情
                $detail = getDatas('delivery_note_detail',['*'],['delivery_note_id'=>$v['id']]);
                if(!empty($detail)){
                    foreach ($detail as $k1 => $v1) {
                        $detail[$k1]['proInfo'] = getProAndProchar($v1,$this->lang);
                        $detail[$k1]['remark'] = getValue('delivery_note_remark',['detail_id'=>$v1['id']],'remark');
                        $detail[$k1]['create_name'] = getValue('admin',['id'=>$v['create_id']],'nickname');
                        $detail[$k1]['create_time'] = date('Y-m-d H:i:s',$v['create_at']);
                    }
                }
                $data[$k]['detail'] = $detail;

                // 装箱单
                $Sale_pack = new Sale_pack();
                $data[$k]['salePackData'] = $Sale_pack->getprodata($v['sale_id'],$this->lang);
            }
        }
        return $data;
    }


    function getpaymentList($id,$pay)
    {
        $res = getDatas('sale_pay_plan',['*'],['sale_id'=>$id]);
        foreach ($res as $k => $v) {
            $res[$k]['content'] = getValue('multi_lang',['mkey'=>'sale_pay_type_'.$v['paytype_id'],'lang'=>$this->lang],'content');
            $res[$k]['paymentDay'] = getTimeDates($v['pay_day'],$this->lang,true);
            $res[$k]['paymentAmount'] = $v['amount'];
            $res[$k]['paymentPercentage'] = $pay > 0 ?  round($v['amount']/$pay*10000)/100 : 0;
            $res[$k]['create_name'] = getValue('admin',['id'=>$v['create_id']],'nickname');
            $res[$k]['create_at'] = getTimeDates($v['create_at'],$this->lang,true);
            // $res[$k]['haspayery'] = getValue('sale_pay_index',['sale_payplan_id'=>$v['id']],'sale_payreg_id');
            $res[$k]['haspayery'] = getDatas('sale_pay_index',['sale_payreg_id'],['sale_payplan_id'=>$v['id']]) ? 1 : 0;
            $remarksList = getDatas('sale_payplan_remark',['*'],['sale_payplan_id'=>$v['id']]);
            // dump($remarksList);die;
            foreach ($remarksList as $k1 => $v1) {
                // dump($v1);die;
                $res[$k]['remarksList'][$k1]['create_at'] = getTimeDates($v1['update_at'],$this->lang,true);
                $res[$k]['remarksList'][$k1]['create_name'] = getValue('admin',['id'=>$v1['update_id']],'nickname');
                $res[$k]['remarksList'][$k1]['content'] = $v1['remark'];
                $res[$k]['remarksList'][$k1]['id'] = $v1['id'];
            }
        }
        // dump($res);die;
        return $res;
    }
    // 获取代金券
    function getVoucher($company_id)
    {
        $res = getDatas('voucher',['*'],['sign_id'=>['gt',0],'used_day'=>['eq',0],'valid_day'=>['gt',time()],'co_id'=>$company_id]);
        foreach ($res as $k => $v) {
            $res[$k]['valid_time'] = getTimeDates($v['valid_day'],$this->lang,true);
        }
        return $res;
    }
    // 获取银行
    function getBank()
    {
        $res = getDatas('banks',['id,id banks_id,name'],['country_id'=>1]);
        return $res;
    }
    // 获取转账支付账号
    function co_bank($company_id)
    {
        $res = getDatas('co_bank',['id,bankname,account_num'],['co_id'=>$company_id]);
        return $res;
    }

    function accounts()
    {

        if ( session('admin')['position_id'] != 1) {
            //获取支付账号
            $whereacc[] = ["exp", "FIND_IN_SET($admin_id,admin_ids)"];
        }
        //收款账号
        $whereacc[] = ["exp", "FIND_IN_SET('1',is_payment)"];

        $whereacc['a.is_public'] = 1;//是否公开
        $whereacc['a.country_id'] = 1;//国家
        //支付账号
        $accountname = Db::name('accounts')->alias('a')->join('nt_banks b', 'a.banks_id=b.id', 'left')->field('a.id,a.bankname,a.account_num accoun,a.is_main,b.name')->where($whereacc)->select();
        return $accountname;
    }

    // 获取产品运费和年销售量
    function getProSale($pro_id,$prochar_id,$value)
    {
        $res = getValue('pro_sale',['pro_id'=>$pro_id,'prochar_id'=>$prochar_id],$value);
        if(!$res) $res = 0;
        return $res;
    }


    // 计算产品当前库存
    function proStore($pro_id,$prochar_id)
    {
        $res = Db::name('store')->where(['pro_id'=>$pro_id,'prochar_id'=>$prochar_id,'warehouse_id'=>0,'place_id'=>0])->value('qty');
        return $res;
    }

    // 计算销售订单 产品详情的 库存状态
    function proStoreStatus($pro_id,$prochar_id,$prochar_qty)
    {
        $storeNum = $this->proStore($pro_id,$prochar_id) ;   // 库存
        $storeNum = $storeNum ? $storeNum : 0;
        $sale_qty_1y = $this->getProSale($pro_id,$prochar_id,'sale_qty_1y');   // 获取一年的销售数量
        if($storeNum/$prochar_qty <= 2) $status = $storeNum;     //  具体数据 存库 <= 2件
        if($storeNum < (($sale_qty_1y/12)/2)) $status = 9;      // s少量
        if($storeNum > (($sale_qty_1y/12)/2)) $status = 8;      // 多
        if($storeNum > ($sale_qty_1y/12)) $status = 7;          // 充足
        $data['sale_qty_1y'] = $sale_qty_1y;
        $data['status'] = $status;
        // return $status;
        return $data;
    }

    // 查询是否需要外调 和期货
    function isNormalSaleOrder($pro_id,$prochar_id,$qty)
    {   
        $admin_department_id = session('admin')['department_id'];
        $admin_warehouse_id = getValue('warehouse2admin',['admin_id'=>$this->user_id],'warehouse_id');
        // 获取所有仓库部门Id
        $department_ids = getDatas('department',['id'],['pid'=>25]);
        $department_ids = array_column($department_ids, 'id');
        $department_ids[] = 25;
        $department_ids[] = 1;  // 管理员
        // dump($department_ids);die;
        // 总仓库库存
        $storeQty = getValue('store',['warehouse_id'=>0,'pro_id'=>$pro_id,'prochar_id'=>$prochar_id],'qty');
        $mainMainWarehouseQty = $storeQty  == null ? 0 : $storeQty;
        $subWarehouseQty = 0;
        $subWarehouseQty = getValue('store',['pro_id'=>$pro_id,'prochar_id'=>$prochar_id,'warehouse_id'=>$admin_warehouse_id],'qty');
        // $storeQty = getValue('store',['pro_id'=>$pro_id,'prochar_id'=>$prochar_id,'warehouse_id'=>0],'qty');
        if($qty){
            $storeStatus = '';
            // 订单qty  大于所有库存，则当前产品订单为期货状态
            if($qty > ((int)$subWarehouseQty + (int)$storeQty) )  $storeStatus = 'futures';
            // 订单qty 大于分仓库qty 小于所有仓库qty 则当前产品订单为外调状态
            if( ($qty > $subWarehouseQty) && ($qty < $storeQty)) $storeStatus = 'outGet';
            return $storeStatus;
        } else{
            $data['subWarehouseQty'] = $subWarehouseQty ? $subWarehouseQty : 0;
            $data['storeQty'] = $storeQty ? $storeQty : 0;
            return $data;
        }

    } 

    function getInvoiceType()
    {
        return getDatas('sale_invoice_type',['*'],'1=1');
    }

    function dataDel()
    {
        $res = 0;
        if($this->data['id']){
            
            $content = '销售单';
            if($this->data['table'] == 'future') $content = '期货';
            // 如果是销售单，如果还没有开始配货，也没付钱是可以删除的
            if($this->data['table'] == 'sale'){
                if(hasData('sale_make',['sale_id'=>$this->data['id']])) return json_encode(array('status'=>2,'msg'=>$content.'删除失败，已经开始配货'));
                if(hasData('sale',['id'=>$this->data['id'],'paid'=>['gt',0]])) return json_encode(array('status'=>2,'msg'=>$content.'删除失败，已收到部分货款'));
            }
            $res = updateData($this->data['table'],['id'=>$this->data['id']],['del_id'=>$this->user_id,'del_at'=>time()]);
            
        }
        if($res){
            return json_encode(array('status'=>1,'msg'=>$content.'删除成功'));
        }else{
            return json_encode(array('status'=>2,'msg'=>$content.'删除失败'));
        }
    }

    function insertSaleLog_($sale_id,$oldData,$newData,$pro_name,$model)
    {   
        $model = $model ? ',型号：'.$model : ',型号：-';
        if($oldData['qty'] != $newData['qty']){
            $aa = '编辑产品：'.$pro_name.$model.' 的数量，编辑前的数量：'.$oldData['qty'].' PCS';
            $this->insertSaleLog($sale_id,$aa);
        }
        if($oldData['price'] != $newData['price']){
            $this->insertSaleLog($sale_id,'编辑产品：'.$pro_name.$model.' 的价格，编辑前的单价：'.$oldData['price'].' BRL');
        }
        
    }

    function insertSaleLog($sale_id,$remark)
    {
        $data['sale_id'] = $sale_id;
        // $data['delivery_id'] = ??;
        $data['remark'] = $remark;


        $data['create_at'] = time();
        $data['create_id'] = $this->user_id;
        $res = insertData('sale_log',$data);
    }

    function getSaleLog($sale_id)
    {
        $return = getDatas('sale_log',['*'],['sale_id'=>$sale_id]);
        foreach ($return as $k => $v) {
            $return[$k]['create_name'] = getValue('admin',['id'=>$v['create_id']],'nickname'); 
            $return[$k]['create_time'] = getTimeDates($v['create_at'],$this->lang,true);
        }
        return $return;
    }

    function getCoSale($co_id,$branch_id)
    {
        $where['branch_id'] = $branch_id;
        if($co_id > 0){
            $where['co_id'] = $co_id;
        }
        
        $coSaledata = Db::name('co_sale')->field('makefirst,pledge,pay_type_ids,delivery_id')->where($where)->find();

        if(!$coSaledata){
            $return['coSaledata'] = []; 
            $return['salePayType'] = $this->getSalePpayType($co_id,'');
        } else{
            $return['coSaledata'] = $coSaledata; 
            $return['salePayType'] = $this->getSalePpayType($co_id,$coSaledata['pay_type_ids']);
        }
        return $return;
    }


    // 获取支付方式
    function getSalePpayType($co_id,$ids)
    {
        $join  = [['multi_lang mu','zu.mkey = mu.mkey']];
        $field = ['zu.id,zu.limit,mu.content'];
        if($ids){
            $where = ['zu.id'=>['in',$ids],'mu.lang'=>$this->lang];
        }else{
            $where = ['mu.lang'=>$this->lang];
        }
        $salePayType = getSearch('sale_pay_type','zu',$field,$where,$join,'zu.id asc');

        foreach ($salePayType as $k => $v) {
            $fail = getValue('co_sale_fail',['pay_type_id'=>$v['id'],'co_id'=>$co_id],'fail');
            $salePayType[$k]['fail'] = $fail ? $fail : 0;
        }
        return $salePayType;
    }


    function deliveryNoteList()
    {
        if(isset($this->data['requestType']) && $this->data['requestType'] == 'index' ){

            $field = ['zu.id,zu.priority,zu.delivery_type_id,zu.co_id,zu.co_branch_id,c.name company_name,cb.name branch_name'];
            $where['zu.id'] = $this->data['sale_id'];
            $join = [
                        ['company c','zu.co_id = c.id'],
                        ['co_branch cb','zu.co_branch_id = cb.id','LEFT'],
                    ];
            $data = getSearch('sale','zu',$field,$where,$join,'zu.id desc');
            // dump($data);die;
            if(!empty($data)){
                $data = $data[0];
                $data['branch_name'] = $data['branch_name'] ? $data['branch_name'] : '' ;
                $detail = getDatas('sale_detail',['*'],['sale_id'=>$data['id']]);
                if(!empty($detail)){
                    foreach ($detail as $k => $v) {
                        $detail[$k]['proInfo'] = getProAndProchar($v,$this->lang);
                        // $detail[$k]['remark'] = getDatas('sale_remark',['id,remark'],['sale_detail_id'=>$v['id']]);
                    }
                }
                $data['detail'] = $detail;
            }
            $deliveryNote = [];
            if($this->data['viewType'] == 'edit'){
                $deliveryNote = Db::name('delivery_note')->where(['id'=>$this->data['deliveryNoteId']])->find();
                if(!empty($deliveryNote)){
                    $deliveryNote['remark'] = getValue('delivery_note_remark',['delivery_note_id'=>$deliveryNote['id'],'detail_id'=>0],'remark');
                    $deliveryNoteDetail = getDatas('delivery_note_detail',['*'],['delivery_note_id'=>$deliveryNote['id']]);
                    if(!empty($deliveryNoteDetail)){
                        foreach ($deliveryNoteDetail as $k1 => $v1) {
                            $deliveryNoteDetail[$k1]['proInfo'] = getProAndProchar($v1,$this->lang);
                            $deliveryNoteDetail[$k1]['remark'] = getValue('delivery_note_remark',['detail_id'=>$v1['id']],'remark');
                        }    
                    }
                    $deliveryNote['detail'] = $deliveryNoteDetail;
                }
            }

            $returnData['branchCompany'] = getDatas('co_branch',['id,name'],['co_id'=>$data['co_id']]);
            $returnData['saleData'] = $data;
            $returnData['deliveryNote'] = $deliveryNote;
            $returnData['pageSum'] = 0;
            return json_encode(array('status'=>1,'data'=>$returnData));

        }else if(isset($this->data['requestType']) && $this->data['requestType'] == 'save' ){
            // dump($this->data);die;
            if($this->data['viewType'] == 'add'){
                $res = $this->implementDeliveryNote($this->data['data'],$this->data['data']['sale_id'],$this->data['viewType']);
                $aa = '添加';
            }else{
                if( isset($this->data['data']['detail']) ){
                    $res = $this->implementDeliveryNote($this->data['data'],$this->data['data']['sale_id'],$this->data['viewType']);
                }else{
                    $res = deleteData('delivery_note',['sale_id'=>$this->data['data']['sale_id']]);
                    $res = deleteData('delivery_note_detail',['sale_id'=>$this->data['data']['sale_id']]);
                    $res = deleteData('delivery_note_remark',['sale_id'=>$this->data['data']['sale_id']]);
                }  

                if(isset($this->data['delDetail_ids']) && $this->data['delDetail_ids']){
                    deleteData('delivery_note_detail',['id'=>['in',$this->data['delDetail_ids']]]);
                    deleteData('delivery_note_remark',['detail_id'=>['in',$this->data['delDetail_ids']]]);
                }  
                $aa = '编辑';
            }

            if($res >= 0){
                $this->countSaleDetail($this->data['data']['sale_id']);
                return json_encode(array('status'=>1,'msg'=>'销售单：'.str_pad($this->data['data']['sale_id'],4,'0',STR_PAD_LEFT).' '.$aa.'送货单成功'));
            }else{
                return json_encode(array('status'=>1,'msg'=>'销售单：'.str_pad($this->data['data']['sale_id'],4,'0',STR_PAD_LEFT).' '.$aa.'送货单失败'));
            }

        }else{
            $deliveryNoteId = 0;
            if(isset($this->data['deliveryNoteId']) && $this->data['deliveryNoteId']) $deliveryNoteId = $this->data['deliveryNoteId'];
            if($this->data['viewType'] == 'add'){
                $title="添加送货单";
            }else{
                $title="编辑送货单";
            }
            return view('deliverynote',['sale_id'=>$this->data['id'],'viewType'=>$this->data['viewType'],'deliveryNoteId'=>$deliveryNoteId,'title'=>$title]);
        }
    }

    // 重新计算销售单明细的未送货数据
    function countSaleDetail($sale_id)
    {
        $saleDetail = getDatas('sale_detail',['*'],['sale_id'=>$sale_id]);
        if(!empty($saleDetail)){
            foreach ($saleDetail as $k => $v) {
                $qty_ = Db::name('delivery_note_detail')->where(['pro_id'=>$v['pro_id'],'prochar_id'=>$v['prochar_id'],'sale_id'=>$sale_id])->sum('qty');
                updateData('sale_detail',['id'=>$v['id']],['undone_qty'=>$v['qty']-$qty_]);
            }
        }
    }

    // 送货单暂停
    function deliveryNoteLock()
    {
        if( isset($this->data['id']) && $this->data['id']){
            $res = updateData('delivery_note',['id'=>$this->data['id']],['lock_at'=>time()]);
            if($res){
                return json_encode(array('status'=>1,'msg'=>'送货单号：'.str_pad($this->data['id'],4,'0',STR_PAD_LEFT).' 暂停成功' ));
            }else{
                return json_encode(array('status'=>1,'msg'=>'送货单号：'.str_pad($this->data['id'],4,'0',STR_PAD_LEFT).' 暂停失败' ));
            }
        }
    }

}